admin管理员组

文章数量:1397686

I'm trying to achieve something like this example in Typescript:

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

export type FruitType = appleOption | orangeOption   //the piler 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; 

Instead of typing out the union types as literal strings for FruitType, I'm hoping to use variables so that when I need to use the value again, I don't have to rewrite them out as magic strings, but as variables which I can refactor easily at a later time. I was trying to see if I could have an alternative to numeric enums in Typescript.

Is it possible to make use of a variable's value as one of the union type options?

I'm trying to achieve something like this example in Typescript:

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

export type FruitType = appleOption | orangeOption   //the piler 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; 

Instead of typing out the union types as literal strings for FruitType, I'm hoping to use variables so that when I need to use the value again, I don't have to rewrite them out as magic strings, but as variables which I can refactor easily at a later time. I was trying to see if I could have an alternative to numeric enums in Typescript.

Is it possible to make use of a variable's value as one of the union type options?

Share Improve this question edited Aug 27, 2016 at 5:11 Carven asked Aug 26, 2016 at 15:42 CarvenCarven 15.7k30 gold badges124 silver badges185 bronze badges 3
  • It sounds like you want an enum. – ssube Commented Aug 26, 2016 at 16:19
  • @ssube yes, but a string enum, which is what I'm trying to emulate. – Carven Commented Aug 26, 2016 at 16:20
  • If I understand what you are trying to do, the answer is no, you can't, at least not as you are trying to do. – user663031 Commented Aug 27, 2016 at 5:41
Add a ment  | 

1 Answer 1

Reset to default 7

If you don't want to use Enums, you can define an actual string as one of the union types:

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

Or if you want to have a separate type for every string:

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

本文标签: javascriptIs it possible to use variable values as one of the union types in TypescriptStack Overflow