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

Time:07-11

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.

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?

CodePudding user response:

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

  • Related