Typescript 基于接口的静态属性的类型

Typescript 基于接口的静态属性的类型,typescript,Typescript,我有多个接口,它们都有一个名为id的属性,这是每个接口的唯一静态字符串 例如: interface Cat{ id: 'cat', furColor: string, likeMice: boolean, } interface Dog { id: 'dog', watchDogSkillLevel: number } 然后我有另一个接口,它有一个proprety to,需要是上述接口的id之一。 我知道我可以使用string,但如果可能的话,我想使用TypeScript

我有多个接口,它们都有一个名为
id
的属性,这是每个接口的唯一静态字符串

例如:

interface Cat{
  id: 'cat',
  furColor: string,
  likeMice: boolean,
}

interface Dog {
  id: 'dog',
  watchDogSkillLevel: number
}
然后我有另一个接口,它有一个proprety to,需要是上述接口的id之一。 我知道我可以使用
string
,但如果可能的话,我想使用TypeScript类型检查

interface Toy {
  forAnimal: string, // <- how to restrict this to id of either Dog or Cat
}
接口玩具{
对于animal:string,//我建议您使用一个来定义所有可能的动物。您必须将它们全部指定一次,然后才能在两种情况下使用它

例如:

enum Animal {
   cat = 'cat',
   dog = 'dog'
}

interface Cat{
  id: Animal.cat,
  furColor: string,
  likeMice: boolean,
}

interface Dog {
  id: Animal.dog,
  watchDogSkillLevel: number
}

interface Toy {
  forAnimal: Animal // can be dog or cat
}

如果您想使用类型检查,您需要向Typescript列出允许哪些动物或允许哪些字符串;否则Typescript将无法确定地告诉您意外值(
jackalope
unicorn
)不允许。在AlesD的回答中,您可以这样做。另一种策略是将可能的动物接口列为类型联合,并让Typescript推断可能的字符串

类型动物=猫|狗;
类型AnimalId=动物[“id”];
界面玩具{
动物纲:动物纲,
}
这允许您在接口中定义
id
s,并且只定义一次联合类型;如果您有一个唯一的静态字符串来确定类型,我希望您已经有了一个。这也足以让Typescript根据字符串推断类型(作为:

功能过程动物(动物:动物){
如果(animal.id==“cat”){
animal.likeMice=真;
}否则{
animal.watchDogSkillLevel=9001;
}
}

换句话说,除了“这100个特定字符串中的一个”之外,您如何描述这种类型?如果您正在查看代码(忘记TypeScript),您会使用什么规则来确定字符串“kangaroo”是否对动物有效?