TypeScript Version: 2.2.1
Code
type LimitedFieldName = "name" | "email" | "phone";
interface ObjectWithLimitedField {
[key: LimitedFieldName]: string;
}
// not ok
type AnyFieldName = string;
interface ObjectWithAnyField {
[key: AnyFieldName]: string;
}
// not ok
interface ObjectWithStringField {
[key: string]: string;
}
// ok
Expected behavior:
Index signature should allow types that evaluate to string or subset of string. The same for number.
Actual behavior:
Any literal other than string and number is explicitly disallowed.
For your first example, see Mapped Types.
type Keys = 'option1' | 'option2';
type Flags = { [K in Keys]: boolean };
WRT using string type aliases as the index type for interfaces, etc., I believe this is being worked on, but I don't remember which issue is tracking it.
See #5683
Or #7374
@LOZORD , thanks, I must have missed that.
@RyanCavanaugh, sorry, closing.
Most helpful comment
For your first example, see Mapped Types.
WRT using
stringtype aliases as the index type for interfaces, etc., I believe this is being worked on, but I don't remember which issue is tracking it.