在TypeScript中,我们可以使用字符串文字类型来执行以下操作:
type HelloString = "Hello";
Run Code Online (Sandbox Code Playgroud)
这让我可以定义类似字符串枚举的内容,如下所示:
namespace Literals {
export type One = "one";
export type Two = "two";
}
Run Code Online (Sandbox Code Playgroud)
然后我可以定义一个联合:
type Literal = Literals.One | Literals.Two;
Run Code Online (Sandbox Code Playgroud)
有没有一种方法来提取的独特价值Literals.One作为类型Literals.One?
原因是,当我定义这样的函数时:
function doSomething(literal : Literal) {
}
Run Code Online (Sandbox Code Playgroud)
我真的很想做以下事情:
doSomething(Literals.One);
Run Code Online (Sandbox Code Playgroud)
但我不能.我要写:
doSomething("one");
Run Code Online (Sandbox Code Playgroud)
可以使用自定义转换器 ( 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'
Run Code Online (Sandbox Code Playgroud)
您可以在命名空间中具有相同名称的类型和值,因此您可以为这些值定义常量:
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);
Run Code Online (Sandbox Code Playgroud)
github上有一个关于字符串枚举的问题,他们建议当前最好的解决方案就是上面的例子.
| 归档时间: |
|
| 查看次数: |
824 次 |
| 最近记录: |