相关疑难解决方法(0)

如何从 TypeScript 中的字符串数组创建类型?

基于字符串数组制作 TypeScript 类型的最佳方法是什么?我使用的是 2.6.2 版。该数组很长,我不想通过复制 Enum 声明中的字符串值来重复自己。

我想做的是这样的:

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
export type Color = convertStringArrayToType(colors);
Run Code Online (Sandbox Code Playgroud)

以下解决方案(源代码)工作正常,但感觉很糟糕:

/** Utility function to create a K:V from a list of strings */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}

/**
  * Sample create a string enum
  */

/** Create a K:V */
const Direction = strEnum([
  'North', …
Run Code Online (Sandbox Code Playgroud)

typescript typescript2.0

14
推荐指数
1
解决办法
7811
查看次数

标签 统计

typescript ×1

typescript2.0 ×1