How to append to a compile time const
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?
Solution 1:
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
.