Skip to content

Index signatures for symbols and template literal strings - #44512

Merged
Anders Hejlsberg (ahejlsberg) merged 59 commits into
mainfrom
moreIndexSignatures
Jun 21, 2021
Merged

Index signatures for symbols and template literal strings#44512
Anders Hejlsberg (ahejlsberg) merged 59 commits into
mainfrom
moreIndexSignatures

Conversation

@ahejlsberg

@ahejlsberg Anders Hejlsberg (ahejlsberg) commented Jun 8, 2021

Copy link
Copy Markdown
Member

With this PR we implement support for symbol and template literal string index signatures. We furthermore permit index signature declarations to specify union key types, provided all constituents are either string, number, symbol, or template literal types with non-generic placeholders. Some examples:

type SymbolMap<T> = {
    [key: symbol]: T;
};

type DataProps = {
    [key: `data-${string}`]: string;
};

type PropertyMap = {
    [key: string | number | symbol]: string;
};

An index signature declaration that specifies a union key type is exactly equivalent to a set of distinct index signatures for each constituent key. For example, the PropertyMap declaration above is exactly equivalent to:

type PropertyMap = {
    [key: string]: string;
    [key: number]: string;
    [key: symbol]: string;
};

Index signature declarations are not permitted to specify literal key types or generic key types. Those kinds of types can only be used with mapped types, which map literals key types to distinct properties and defer resolution of generic key types until they're instantiated with non-generic types. For example:

type Thing<T> = Record<'a' | `foo${T}` | symbol, string>;

type StringThing = Thing<string>;  // { [a: string, [x: `foo${string}`]: string, [x: symbol]: string }
type BarThing = Thing<'bar'>;  // { [a: string, foobar: string, [x: symbol]: string }

This PR supercedes #26797 which was more ambitious but had overlap between regular properties and index signatures with literal key types that is difficult to reconcile, as well as generic index signatures for which type relationships become exceedingly complex to reason about.

Fixes #1863.
Fixes #26470.
Fixes #42192.
Fixes #44675.