Skip to content

Using string enum as key in {[key]: Type} throws not an index signature #22892

Closed
@appsforartists

Description

@appsforartists

TypeScript Version: 2.9.0-dev.20180325

Search Terms: string enum index signature cast

Code

enum Fruits {
    MANGO = 'MANGO',
    BANANA = 'BANANA',
}

type StringDict = { [key: string]: string };

function map(dict: StringDict, transform: (key: string, value: string) => void) {
    const result = {};

    for (const key of Object.keys(dict)) {
        result[key] = transform(key, dict[key]);
    }

    return result;
}

map(Fruits, (key, value) => {
    value.toLowerCase();
});


map(Fruits as StringDict, (key, value) => {
    value.toLowerCase();
});

Expected behavior:
Both map calls succeed, because a string enum is essentially a {[key: string]: string}. I ought to be able to use it anywhere that needs something indexed by string (as long as the values are appropriate).

Actual behavior:
index.ts(14,5): error TS2345: Argument of type 'typeof Fruits' is not assignable to parameter of type 'StringDict'.
Index signature is missing in type 'typeof Fruits'.
index.ts(19,5): error TS2352: Type 'typeof Fruits' cannot be converted to type 'StringDict'.
Index signature is missing in type 'typeof Fruits'.

Playground Link

Related Issues:
#20011, #18029, #16760

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions