Typescript: An index signature parameter type must be 'string' or 'number' - why not its's equivalent?

Created on 30 Mar 2017  路  4Comments  路  Source: microsoft/TypeScript

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.

Duplicate

Most helpful comment

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.

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

seanzer picture seanzer  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

dlaberge picture dlaberge  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments