在TypeScript中,我们可以使用字符串文字类型来执行以下操作:
type HelloString = "Hello";
这使我可以定义类似于字符串枚举的内容,如下所示:
namespace Literals {
export type One = "one";
export type Two = "two";
}
然后我可以定义一个联合:
type Literal = Literals.One | Literals.Two;
有没有一种方法来提取的独特价值Literals.One
作为类型Literals.One
?
这样做的原因是,当我定义这样的函数时:
function doSomething(literal : Literal) {
}
我真的很想做到以下几点:
doSomething(Literals.One);
但是我不能。我必须写:
doSomething("one");
您可以在名称空间中使用具有相同名称的类型和值,因此可以为这些值定义常量:
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);
github上有一个关于字符串枚举的问题,他们建议当前的最佳解决方案是上面的示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句