Interpolated string type can't be used to index record with the same type as key

Viewed 40

I'm trying to use an interpolated string type to index a Record type using a key that should match the key type of the record. However it does not seem to be working.

Here's a minimal example:

type TypeOfKey = `chart-${number}`|`text-${number}`;
// type TypeOfKey = string; // It works when KeyType is this type

interface ReportComponent {
    identifier: TypeOfKey;
}

interface Report {
    components: Record<TypeOfKey, ReportComponent>;
}

const component : ReportComponent = {
    identifier: 'text-2'
};

const report : Report = {
    components: {
        'text-2': component
    }
};


if (report.components[component.identifier] !== undefined) {  // Element implicitly has an 'any' type because expression of type 'TypeOfKey' can't be used to index type 'Record<TypeOfKey, ReportComponent>'
    // do something
}

I'm not sure why this is happening. As noted in the code, if I just use string as TypeOfKey it works.

Playground link

1 Answers
Related