Skip to content

String enum can't be used to index into an object #16760

Closed
@zakjan

Description

@zakjan

TypeScript Version: 2.4.0

Code

enum Name {
    A = "a",
    B = "b",
    C = "c",
}

// interfaces with computed property names are not supported yet, see https://github.com/Microsoft/TypeScript/issues/5579
interface Item {
    /* [Name.A] */ a: string;
    /* [Name.B] */ b: number;
    /* [Name.C] */ c: boolean;
}

const names: Name[] = [Name.A, Name.B, Name.C];

const item: Item = {
    [Name.A]: "a",
    [Name.B]: 1,
    [Name.C]: true,
};

names.forEach((name: Name) => {
    console.log(item[name]);
});

Expected behavior:
No errors are thrown (ideally also when using the commented code with computed interface property names).

Actual behavior:

src/test.ts(16,7): error TS2322: Type '{ [x: string]: string | number | boolean; }' is not assignable to type 'Item'.
  Property 'a' is missing in type '{ [x: string]: string | number | boolean; }'.
src/test.ts(23,17): error TS7017: Element implicitly has an 'any' type because type 'Item' has no index signature.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions