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
1 Answer
Reset to default 7If 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
版权声明:本文标题:javascript - Is it possible to use variable values as one of the union types in Typescript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744166522a2593576.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论