网站搜索

typescript - 当判别字段有重叠时,如何缩小对象类型的联合?


我下面有一个类型:

type Animal = {
  kind: 'cat';
  params: string;
} | {
  kind: 'dog';
  params: number[];
} | {
  kind: string;
  params: Record<string, string>
}

当我尝试使用 switch 缩小 Animal 类型时,它不能缩小到具体的对象类型。

switch (animal.kind) {
  case 'cat':
    console.log(animal.params.toUpper())  // Error: animal.params is a type of `string | Record<string, string>`
    break;
  case 'dog':
    console.log(animal.params.length)
    break;
  default:
    console.log("animal is an object");
}

但是这不起作用。在第一个 case 中,它认为 params 是 string | Record<string, string>。

我理解这是因为 string 和 "cat" 有重叠,但我该如何让这种缩小发生?

答案#1

正如 @jcalz 在问题的评论中提到的,这似乎是 TypeScript 的设计限制。

根据这里的评论,Typescript 需要做类似于否定类型的东西(string - cat - ...),而 Typescript 并不是设计来以这种方式分解联合类型的。