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

How to append to a type

We have a type declared as following.

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

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

Such as:

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

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?

>Solution :

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.

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