使用非类型文字字段作为标签时,类型缩小不起作用

问题描述 投票:0回答:1

test
函数内部,当
b
类型为
string
时,
a
类型不会缩小为
string

为什么?我不明白为什么它会这样。

type Foo = {
  a: string;
  b: string;
};
type Bar = {
  a: number;
  b: number;
};

type Uinon = Foo | Bar;

function test({ a, b }: Uinon) {
  if (typeof a === "string") {
    a;
    b;
  }
}

游乐场

如果 a 是如下所示的类型文字,这很好,但是如果它不是类型文字,为什么它不是类型缩小?

type Foo = {
  a: "A";
  b: string;
};
type Bar = {
  a: "B";
  b: number;
};
typescript type-narrowing
1个回答
0
投票

您使用的功能不是类型缩小,而是歧视联合。来自(显然已过时)[文档][1]:

歧视性工会

使用联合的常见技术是使用一个使用“文字类型”的字段,您可以使用它来让 TypeScript 缩小可能的当前类型范围。例如,我们将创建具有单个共享字段的三种类型的联合。

并且这种区分仅针对文字类型实现。 [1]:
https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#discriminating-unions

© www.soinside.com 2019 - 2024. All rights reserved.