Skip to content

Combine index signature (of union of string literal type) with other keys #20159

@mhchem

Description

@mhchem

TypeScript Version: 2.6.1

The Code I want to move to TS makes use several times of this (simplified) pattern:

let e = {
    a: 1,
    "b": 2,
    c: 3,
    get: (i) => e[i] + "."
}

Here is the same code annotated with types.

type Kinds = "a"|"b"|"c"

// This works.
type DObjects = {
    [key in Kinds]: number;
}
let d: DObjects = {
    a: 1,
    "b": 2,
    c: 3
}

// This does not work yet ...
type EObjects = {
    [key in Kinds]: number;
    get: { (i: Kinds): string };
}
let e: EObjects = {
    a: 1,
    "b": 2,
    c: 3,
    get: (i) => e[i] + "."
}

But this does not work, although this should be equivalent to

// ... but should be equivalent to this.
type FObjects = {
    a: number;
    b: number;
    c: number;
    get: { (i: Kinds): string };
}
let f: FObjects = {
    a: 1,
    "b": 2,
    c: 3,
    get: (i) => f[i] + "."
}

Expected behavior:

Treat [index in Kinds] (where Kinds is a union of string literal types) the same way as if one would type them explicitly.

Actual behavior:

issue.ts(16,5): error TS1005: '}' expected.
issue.ts(16,31): error TS1005: '=>' expected.
issue.ts(17,1): error TS1128: Declaration or statement expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions