2016-11-07 15 views
2

在打字稿,我们可以有字符串字面类型,使我们能够做的事情一样:打开一个字符串类型的文字值

type HelloString = "Hello"; 

这让我这样定义字符串枚举的东西如下:

namespace Literals { 
    export type One = "one"; 
    export type Two = "two"; 
} 

,然后我可以定义一个联盟:

type Literal = Literals.One | Literals.Two; 

有没有一种方法来提取的的独特价值作为Literals.One的类型?

这样做的原因是,当我这样定义一个函数:

function doSomething(literal : Literal) { 

} 

我真的很想做到以下几点:

doSomething(Literals.One); 

但我不能。我必须写:

​​

回答

4

你可以有类型和值与命名空间中的名称相同,所以你可以对这些值定义常量:

namespace Literals { 
    export type One = "one"; 
    export type Two = "two"; 
    export const One: One = "one"; 
    export const Two: Two = "two"; 
} 

const s: Literals.One = Literals.One; 
console.log(s); 

有一个probosal on github for string enums,他们建议目前最好的解决方案是上面的例子。

1

使用自定义转换器(https://github.com/Microsoft/TypeScript/pull/13940)可以将字符串文字类型转换为文字值,这可以在typescript @ next中找到。

请看我的npm包,ts-transformer-enumerate

实例:

// The signature of `enumerate` here is `function enumerate<T extends string>(): { [K in T]: K };` 
import { enumerate } from 'ts-transformer-enumerate'; 

type Colors = 'green' | 'yellow' | 'red'; 
const Colors = enumerate<Colors>(); 

console.log(Colors.green); // 'green' 
console.log(Colors.yellow); // 'yellow' 
console.log(Colors.red); // 'red'