Skip to content

String literal type operators #12940

@zamb3zi

Description

@zamb3zi

It would be useful if we could combine string literal types to create new types. For example suppose A and B extend string then:

type AB = A + B; // strings formed from a member of A concatenated with a member of B.
type Ax = A + string; // strings starting with a member of A
type xB = string + B; // strings ending with a member of B

This would combine well with mapped types. For example suppose we want to specify an ordering of records of type T to some third-party module that requires SQL-like syntax. We could write:

function orderBy<T>(records: Array<T>, order: (keyof T) + ('' | ' ASC' | ' DESC')) {
    ...
}
let records = [{x: 5}, {x: 2}, {x: 7}];
orderBy(records , 'x');
orderBy(records , 'x DESC');

Maybe some other forms would be useful:

type notA = !A; // any string except for the members of A
type notAx = !A + string; // strings not starting with a member of A
type AxB = A + string + B; // equal to Ax & xB
type xAx = string + A + string; // strings containing a member of A
type A3 = A * 3; // A + A + A

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions