考虑下面的代码片段:
type Foo = {
x: string;
y: number;
};
let a: Foo = {
x: "@",
y: 3,
};
let b: Partial<Foo> = { x: "#", y: undefined };
let c = { ...a, ...b };显然,c的类型不能是Foo,因为属性y是undefined:c的运行时值是{x: "#", y: undefined} (至少在Chrome中是这样)。然而Typescript推断c类型为{ x: string; y: number;}。您可以签入4.0.5版的https://www.typescriptlang.org/play。我很困惑。
编辑:这是从评论到github问题的链接,带有完全相同的问题https://github.com/microsoft/TypeScript/issues/13195#issuecomment-373178677。现在,这就是答案。
发布于 2020-11-23 05:54:15
这里的主要问题是Partial<Foo>类型
let b: Partial<Foo> = { x: "#", y: undefined };当您指定变量type时,ts编译器通常会忽略赋值的右侧,并且不会将其用于类型推断(有一些例外,但通常它是这样工作的)。
https://stackoverflow.com/questions/64959028
复制相似问题