rt,预期当品类species为Cat时,animalsType只能为Cat对应的string。
但实际上animalsType成为了联合类型
代码如下:
type SpeciesType = "Cat" | "Dog" interface AnimalsType { Cat: String Dog: Number } interface Animals<T extends SpeciesType> { species: T animalsType: AnimalsType[T] } const animalList: Animals<SpeciesType>[] = [ // ok { species: "Cat", animalsType: "1", }, // ok { species: "Dog", animalsType: 1, }, // expect:error! // 此处预期结果应该报错,希望从联合类型中取出Cat对应的为string { species: "Cat", animalsType: 1, }, ]
补充说明:
我已经了解到可以将Animals声明为联合类型来解决,但这个方案不适用于我的具体问题
示例如下:
type SpeciesType = "Cat" | "Dog" interface AnimalsType { Cat: String Dog: Number } type Animals = { species: "Cat" animalsType: String } | { species: "Dog" animalsType: Number } // 预期为: const animalList: Animals[] = [ // ok { species: "Cat", animalsType: "1", }, // ok { species: "Dog", animalsType: 1, }, // expect:error! // 此处预期结果应该报错,希望从联合类型中取出Cat对应的为string { species: "Cat", animalsType: 1, }, ]
感觉这个类型可以转化为类型推断问题
将T具体推断为Cat/Dog,从而获取到对应的animalsType
type Animals = { [K in keyof AnimalsType]: { species: K; animalsType: AnimalsType[K] } }[keyof AnimalsType] const animalList: Animals[] = [ // ok { species: "Cat", animalsType: "1", }, // ok { species: "Dog", animalsType: 1, }, // error! { species: "Cat", animalsType: 1, }, ]