Closed
Description
Before You File a Proposal Please Confirm You Have Done The Following...
- I have searched for related issues and found none that match my proposal.
- I have searched the current rule list and found no rules that match my proposal.
- I have read the FAQ and my problem is not listed.
My proposal is suitable for this project
- I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).
Link to the rule's documentation
https://typescript-eslint.io/rules/consistent-indexed-object-style/
Description
When "record"
option is chosen in @typescript-eslint/consistent-indexed-object-style
, we should also be forbidden from using the "in"
keyword in index signature. It's particularly useful for literal types.
Here's the justification:
- we should prefer
Record
versusIndex Signature
whenever we want to use literal types, as index signature accepts onlystring
,number
orsymbol
as key type. - And when
Record
is preferred, it also brings an advantage of ensuring no missing property in literal types -> which further ensures type safety, and avoid getting unexpectedundefined
case from non-existing key. - However, such advantage will not be kept since the current
@typescript-eslint/consistent-indexed-object-style
rule allows people using{ [key in Option] : string}
Fail
/* eslint @typescript-eslint/consistent-indexed-object-style: ["error", "record"] */
type Option = "red" | "yellow";
const optionToString: { [key in Option]: string} = {
"red": "this is red" // won't be warned that "yellow" is missing
}
Pass
/* eslint @typescript-eslint/consistent-indexed-object-style: ["error", "record"] */
type Option = "red" | "yellow";
// if we use Record, it will prompt error if any property is missing;
// E.g. it should say "Property 'yellow' is missing in type '{ red: string; }' but required in type 'Record<Option, string>'."
// if we just have "red" as the only property.
const optionToString: Record<Option, string> = {
"red": "this is red",
"yellow": "this is yellow",
}
// Or, if we indeed want to get undefined for some keys; making them explicit when defining
// the type and value is better and clearer.
const optionToString: Record<Option, string | undefined> = {
"red": "this is red",
"yellow": undefined,
}
Additional Info
No response