signature=a50509fced5624c88b96921619623bb7,Implicit index signatures

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).

你可能感兴趣的:(signature=a50509fced5624c88b96921619623bb7,Implicit index signatures)