Home > Mobile >  How to append to a compile time const
How to append to a compile time const

Time:01-13

We have declared as following.

type colors = "green" | "blue" | "red"; 

Is there a way we could append to it based on a condition?

Such as:

const shouldAppend = // some logic to return true / false.

if (shouldAppend) {
    colors.append('yellow'); // invalid syntax
}

Which should update the type to the following.

colors = "green" | "blue" | "red" | "yellow";

Is it possible to append to a type, and how could I do it?

CodePudding user response:

It is not possible in typescript. You are not allowed to mutate types, however you are allowed to create new one:

type Colors = "green" | "blue" | "red";

type NewColors<T extends string> = Colors | T

// Colors | "yellow"
type Result = NewColors<'yellow'>

Please keep in mind, that there are two scopes in typescript: type scope and value/runtime scope. You are not allowed to use types in runtime scope. I mean, during compilation all types are removed from source code.

Maybe you should try rescript, because it allows you to do almost exactly what you want:

type t = ..

type t  = Other

type t  =
  | Point(float, float)
  | Line(float, float, float, float)

It called Extensible Variant.

CodePudding user response:

You can do this using typeof shouldAppend with a conditional type:

const shouldAppend = true;

type Colors =
    | 'red'
    | 'green'
    | 'blue'
    | (typeof shouldAppend extends true ? 'yellow' : never)

Playground Link

If you don't need to use the value of shouldAppend at runtime, you can make it a type instead of a const:

type ShouldAppend = true

type Colors =
    | 'red'
    | 'green'
    | 'blue'
    | (ShouldAppend extends true ? 'yellow' : never)

Playground Link

  •  Tags:  
  • Related