Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to build dynamic string type based on other custom string type in typescript?

I have prepared simple code to represent the issue. I have a type that accepts a bunch of string, let’s called it Names:

type Names = "field1" | "field2";

Now I need to build a type that will accept also a bunch of new strings based on the Names type.

type Names = "field1" | "field2";

type FieldsNames =
  | "field1_created"
  | "field1_updated"
  | "field1_deleted"
  | "field2_created"
  | "field2_updated"
  | "field2_deleted";

As you can see, for each string (field1, field2) I need to build a type that accepts another three types of string. This already can grow really fast.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to for example, extract keys from Names type and based on that, create new custom types? If so how to do it with typescript?

>Solution :

You need to use distributive conditional types:

type Names = "field1" | "field2";

type Prefix = 'created' | 'updated' | 'deleted'

type FieldsNames =
    | "field1_created"
    | "field1_updated"
    | "field1_deleted"
    | "field2_created"
    | "field2_updated"
    | "field2_deleted";

type Builder<T extends string> = T extends any ? `${T}_${Prefix}` : never

// Result is the same as FieldsNames
type Result = Builder<Names>

type Assert<T, _ extends T> = T

type Test = Assert<Result, FieldsNames> // ok

Playground

T extends any – turns on distributivity

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading