【问题标题】:Is it possible to use variable values as one of the union types in Typescript?是否可以将变量值用作 Typescript 中的联合类型之一?
【发布时间】:2017-01-03 08:18:15
【问题描述】:

我正在尝试在 Typescript 中实现类似这个示例:

const appleOption:string = 'Apple';
const orangeOption:string = 'Orange';

export type FruitType = appleOption | orangeOption   //the compiler wouldn't allow this.

//my intention is for writing of the type be in variable and not their actual strings so that it's easier for me to refactor them in future
const eventType:FruitType = orangeOption; 

我希望使用变量而不是将联合类型输入为 FruitType 的文字字符串,以便当我需要再次使用该值时,我不必将它们重写为魔术字符串,但是作为变量,我可以在以后轻松重构。我试图看看是否可以替代 Typescript 中的数字枚举。

是否可以将变量的值用作联合类型选项之一?

【问题讨论】:

  • 听起来你想要一个enum
  • @ssube 是的,但是一个字符串枚举,这是我想要模拟的。
  • 如果我理解你想要做什么,答案是否定的,你不能,至少不像你想要做的那样。

标签: javascript typescript typescript-typings


【解决方案1】:

如果你不想使用枚举,你可以定义一个实际的字符串作为联合类型之一:

type FruitType = 'orange' | 'apple' | 'banana'
let validFruit: FruitType = 'orange' // compiles fine
let invalidFruit: FruitType = 'tomato' // fails compilation

或者如果你想为每个字符串设置一个单独的类型:

type OrangeType = 'orange'
type AppleType = 'apple'
type FruitType = OrangeType | AppleType

【讨论】:

  • 就像我在问题中提到的那样,我希望有一种方法不会多次编写文字字符串,这样如果我重构,比如将 apple 更改为 apples,它如果它们都是变量会更容易。
  • 把字符串分成不同的类型怎么样?
  • 啊! +1!我怎么没想到!太感谢了! :D
  • 哦等等!实际上,这种技术仍然存在问题。当我声明这样的事件类型时:const eventType:FruitType = OrangeType;,我收到一条错误消息error TS2304: Cannot find name 'OrangeType'.
  • 您为什么要这样做? OrangeType 是一种类型,您不能将其作为值分配给变量。
猜你喜欢
  • 1970-01-01
  • 2021-07-10
  • 2019-12-05
  • 2021-10-26
  • 2018-12-08
  • 2016-07-22
  • 1970-01-01
  • 2018-09-06
  • 2023-01-11
相关资源
最近更新 更多