Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error messages when indexing into a type #31379

Merged
merged 3 commits into from
May 23, 2019

Conversation

dragomirtitian
Copy link
Contributor

Fixes #30241

This PR introduces more explicit error messages when trying to index into a type without an index signature.
Rules:

  • When the index argument is a string literal, number literal or unique symbol, but the target object does not have the corresponding property the error will be:
Element implicitly has an 'any' type because expression of type 'LITERAL_TYPE' can't be used to index type 'TARGET_TYPE'.
  Property 'PROP_NAME' does not exist on type 'TARGET_TYPE'
  • When the index argument is a union of literals, the error message will contain the union used to index, and will contain the first property in the union that is not found in the type:
Element implicitly has an 'any' type because expression of type 'UNION_OF_LITERAL_TYPES' can't be used to index type 'TARGET_TYPE'.
  Property 'FIRST_MISSING_PROP_NAME' does not exist on type 'TARGET_TYPE'
  • When the index argument is string or number the error will warn about the missing index on the target type:
Element implicitly has an 'any' type because expression of type 'STRING_OR_NUMBER' can't be used to index type 'TARGET_TYPE'.
  No index with a parameter of type 'STRING_OR_NUMBER' was found on type 'TARGET_TYPE'

Examples:

const o = { a: 0 };

declare const k:"b";
o[k]; // rule 1
// Element implicitly has an 'any' type because expression of type '"b"' can't be used to index type '{ a: number; }'.
//   Property 'b' does not exist on type '{ a: number; }'

declare const k2: "b" | "c";
o[k2]; // rule 2
// Element implicitly has an 'any' type because expression of type '"b" | "c"' can't be used to index type '{ a: number; }'.
//   Property 'b' does not exist on type '{ a: number; }'.

declare const nIndex: number;
o[nIndex] // rule 3
// Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ a: number; }'.
//   No index with a parameter of type 'number' was found on type '{ a: number; }'

@dragomirtitian dragomirtitian changed the title Gh 30241 Improve error messages when indexing into a type May 13, 2019
@weswigham weswigham merged commit 8ab0a25 into microsoft:master May 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Improve error message for union indexing
3 participants