TypeScript函数泛型类型的交集行为不正确(TypeScript function generic types intersection does not behave correctly)

系统教程 行业动态 更新时间:2024-06-14 17:04:03
TypeScript函数泛型类型的交集行为不正确(TypeScript function generic types intersection does not behave correctly) interface A { a: number; } let myVar: A = { a: 123 }; myVar = Object.assign({}, myVar, { b: 456 });

为什么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

更多推荐

本文发布于:2023-04-24 21:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/4ca68c0f12b8407e3f3dbc929b50e847.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不正确   函数   类型   function   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!