Home > database >  How to split a string into a Records in Typescript?
How to split a string into a Records in Typescript?

Time:04-20

I have a use case where I would like to split a string type into a Record.

Example:

const string = "Thank you"

And I would like to convert it into

Record<'Thank' | 'you', string>

Is there any easy way how to achieve this?

Thanks in advance

CodePudding user response:

You need to use Template literal types

const MY_STRING = "Thank you";
type Split<S extends string, D extends string> =
    string extends S ? string[] :
    S extends '' ? [] :
    S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];

type MY_STRING_PARTS_TUPLE = Split<typeof MY_STRING, ' '>
type MY_STRING_PARTS = MY_STRING_PARTS_TUPLE[number];
type MY_RECORD = Record<MY_STRING_PARTS, string>

Playground link

See also Template literal types playground

  • Related