TypeScript discriminating union - discrimating属性类型的参数

Roe*_*den 8 typescript

我有以下定义:

interface Dog {
  bark(): void;
  type: 'dog';
}

interface Cat {
  meow(): void;
  type: 'cat';
}

type Animal = Cat | Dog;
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个Animal.type用作参数的函数:

function useAnimalType(type: string) {}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我使用过string,但我的意思是'cat' | 'dog'.我意识到我可以写出所有可能typeAnimal,但想象一下当有数百种动物类型被定义时的情景Animal.我如何Animal.type在这里重用参数?

CRi*_*ice 12

您可以使用括号表示法检索另一个对象类型中的字段类型.举个例子,简单地说:

function useAnimalType(type: Animal["type"]) {}
Run Code Online (Sandbox Code Playgroud)

就够了 在这种情况下,Animal["type"]推断是"cat" | "dog".