signature=a50509fced5624c88b96921619623bb7,Implicit index signatures

这篇博客讨论了TypeScript中关于对象字面量类型与带有索引签名类型的赋值兼容性更新。现在,如果对象字面量的所有已知属性都可赋值给目标索引签名,那么该字面量类型可以赋值给该类型。更新还引入了三条新的赋值兼容规则,并移除了自动将上下文类型中的索引签名添加到对象字面量的规则。这减少了错误消息的噪音,并允许更精确地报告不满足索引签名约束的属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Fixes #6041.

With this PR an object literal type is assignable to a type with an index signature if all known properties in the object literal are assignable to that index signature. This makes it possible to pass a variable that was initialized with an object literal as parameter to a function that expects a map or dictionary:

function httpService(path: string, headers: { [x: string]: string }) { }

const headers = {

"Content-Type": "application/x-www-form-urlencoded"

};

httpService("", { "Content-Type": "application/x-www-form-urlencoded" }); // Ok

httpService("", headers); // Now ok, previously wasn't

The PR adds the following three assignment compatibility rules (where an object literal type is the inferred type of an object literal or a type declared using an object type literal with no call or construct signatures):

An object literal type S with no index signatures is assignable to a type T with a string index signature M if each property in S is of a type that is assignable to the type of M.

An object literal type S with no index signatures is assignable to a type T with a numeric index signature M if each numerically named property in S is of a type that is assignable to the type of M.

An object literal type S with no string index signature and a numeric index signature N is assignable to a type T with a string index signature M if the type of N is assignable to the type of M and each property in S is of a type that is assignable to the type of M.

The PR adds corresponding type inference rules.

The PR furthermore removes the rule that adds index signatures to an object literal when it is contextually typed by a type that has index signatures. Instead, the type inferred for an object literal has index signatures only if it contains computed properties. For example:

let s = "hello";

let n = 123;

let o = {

[s]: new Date(),

[n]: new Error()

};

In the above, the type of o is { [x: string]: Date | Error, [x: number]: Error }.

Removing the automatic contextual index signatures from object literal types has the nice effect of reducing noise in our error messages. Also, we can now report the name of the offending property when an object literal doesn't meet the constraint implied by a target index signature (previously you'd have to deduce it yourself from two incompatible union types).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值