typescript - 如何附加到编译时常量

标签 typescript

我们声明如下。

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

有没有一种方法可以根据条件附加到它?

如:

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

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

这应该将类型更新为以下内容。

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

是否可以附加到类型,我该如何做?

最佳答案

这在 typescript 中是不可能的。您不能改变类型,但是可以创建新类型:

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

type NewColors<T extends string> = Colors | T

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

请记住, typescript 中有两个作用域:类型作用域值/运行时作用域。您不得在运行时范围中使用类型。我的意思是,在编译期间,所有类型都会从源代码中删除。

也许你应该尝试rescript ,因为它几乎可以让你做你想做的事:

type t = ..

type t += Other

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

它称为可扩展变体

关于typescript - 如何附加到编译时常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70693377/

相关文章:

javascript - ionic 3 angular 4 http拦截器显示每个请求的加载

typescript - 如何将泛型限制为联合?

javascript - 如何在 mat-form-field 中改变高度

javascript - 如何将对象数组重新映射到新数组中

javascript - 理解柯里化(Currying)函数

module - Visual Studio Code 中 TypeScript 文件中的绝对模块路径解析

javascript - react 接口(interface): Promise works but objects are still "is not defined"

javascript - 如何动态存储HTML元素的信息?

typescript - 如何在 Jest 中使用全局变量并通过 cmd 传递它

typescript - 在子接口(interface)中为父接口(interface)的每个成员添加参数