gpt4 book ai didi

typescript - 为什么 typescript 在这种情况下使用联合类型显示错误?

转载 作者:行者123 更新时间:2023-12-05 09:27:20 25 4
gpt4 key购买 nike

在这种情况下:

type Type = {
a: string;
b: string;
} | {
a: number;
b: number;
};

const func = ({a, b}: Type): string => {
if (typeof a === 'string') {
return b;
}

return 'w/e';
}

func({a: 1, b: 'w/e'});

我在 return b; 上遇到错误,声明

Type 'string | number' is not assignable to type 'string'.

  Type 'number' is not assignable to type 'string'.

根据我对错误的理解,Typescript 将 Type 类型解释为

type Type = {
a: string | number;
b: string | number;
};

,但即使是这样,为什么我不能用字符串和数字调用 func 函数?

调用状态错误

Argument of type '{ a: number; b: string; }' is not assignable to parameter of type 'Type'.

  Type '{ a: number; b: string; }' is not assignable to type '{ a: number; b: number; }'.

    Types of property 'b' are incompatible.

      Type 'string' is not assignable to type 'number'.

(TS 版本:4.7.2)

Playground link

错误类型的函数调用只是为了检验我关于为什么会出现先前错误的假设。为什么我在 return b; 时出错是我不明白的。

最佳答案

好的,答案是Discriminated Unions。我必须在并集的每个元素中使用一个判别式,一个共同的属性。那,判别式,性质:

  1. 必须是原始类型,并且
  2. 必须有一个特定的值,而不是该值的类型。例如isPrimary: true,而不是 isPrimary: boolean

然后我可以检查该属性的值以假定其他属性的类型。

此外,在 Typescript 版本 < 4.6 中,如果我有一个具有上述指定类型的对象,如果我对其进行解构,那么新变量将被视为独立变量,并且我将继续收到类似于初始示例的错误。解构适用于 4.6 或更高版本。

有用的链接:

谢谢@Austaras@coglialoro

关于typescript - 为什么 typescript 在这种情况下使用联合类型显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72572226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com