为什么TypeScript没有抱怨通过Object.assign()调用重新分配myVar ?
鉴于Object.assign()调用的类型定义是:
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;...和我的调用中三种类型的(返回类型)交集与interface A不匹配,编译器不应该选择它吗?
问题与TypeScript无法推断函数调用中的类型无关,因为如果我将代码更改为:
interface A { a: number; } interface B { b: number; } interface C {} let myVar: A = { a: 345 }; myVar = Object.assign<C, A, B>({}, myVar, { b: 345 });......它仍然没有抱怨。
我正在使用TypeScript 2.2.1并且“noImplicitAny”编译器标志设置为“true”。
interface A { a: number; } let myVar: A = { a: 123 }; myVar = Object.assign({}, myVar, { b: 456 });Why does TypeScript not complain about that re-assignment of myVar via the Object.assign() call?
Given that the type definition for that Object.assign() call is:
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;...and the (return type) intersection of the three types in my call doesn't match interface A, shouldn't the compiler pick that up?
The problem is not related to TypeScript not being able to infer the types in the function call, because if I change the code to:
interface A { a: number; } interface B { b: number; } interface C {} let myVar: A = { a: 345 }; myVar = Object.assign<C, A, B>({}, myVar, { b: 345 });...it still doesn't complain.
I'm using TypeScript 2.2.1 and the "noImplicitAny" compiler flag is set to "true".
最满意答案
TypeScript结构类型系统的基本规则是,如果y与x至少具有相同的成员,则x与y兼容
将此规则应用于您的示例 - A与A&B&C兼容:
let abc:A&B&C = {a:123, b:456};并且赋值let a:A = abc; 完全有效。
更多信息在这里
The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x
Applying this rule to your example - A is compatible with A&B&C:
let abc:A&B&C = {a:123, b:456};And assignment let a:A = abc; is perfectly valid.
More info here
更多推荐
发布评论