Closed
Description
Search Terms
union, index
Suggestion
When a type union is used to index into a type with no index signature, if the property names match up correctly the access is allowed and Typescript does the "right thing" anyway. If the property names don't match up, and there's no index signature, an error is given, but it might not be the most helpful error.
Use Cases
I have a type that's a union of string literals, and I want to create some mapping for them. But if I forget a single property name, the error doesn't help me find what was missing
Examples
// noImplicitAny
type Froot = "orange" | "apple" | "banannanana";
const frootsToNames = {
orange: "Orangey",
apple: "Appley",
banannanana: "Kiwiey"
};
const frootsToNamesBroken = {
orange: "Orangey",
apple: "Appley",
bananana: "Kiwiey"
};
declare var f: Froot;
// works fine
frootsToNames[f];
// reports error:
// Element implicitly has an 'any' type because type
// '{ orange: string; apple: string; bananana: string; }' has no index signature
// could report better error:
// Element implicitly has an 'any' type because possible key
// 'banannanana' from type Froot is missing on type '{ orange: string; apple: string; bananana: string; }',
// and no index signature
frootsToNamesBroken[f];
Related
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.