繁体   English   中英

在 TypeScript 中将类型文字转换为字符串文字

[英]Turning type literal into string literal in TypeScript

我意识到这可能违反了 TypeScript 哲学,但我想我还是会问。

是否可以在编译时将类型文字转换为字符串文字?

例如,我可以将"AnotherString"分配给下面的str2而不重复吗?

// object to type, no problem
const obj = "SomeString";
let str1: typeof obj = obj;

// type into obj: ?
type SomeType = "AnotherString";
const str2: SomeType = valueof SomeType; // no such thing as valueof

是否可以在编译时将类型文字转换为字符串文字?

不,因为发出的代码中不存在类型。 它编译成的 JavaScript 是没有所有类型的 TypeScript。 (几乎)TypeScript 提供的一切都是在您编写脚本时为您提供帮助,并且在运行时没有任何影响,因为在编译时它们都会被删除。

这有效

const obj = "SomeString";
let str1: typeof obj = obj;

因为,编译时,它是

const obj = "SomeString";
let str1 = obj;

type SomeType = "AnotherString";
const str2: SomeType = <something referencing SomeType>

不能工作,因为在编译时,类型消失了,所以

const str2 = <something referencing SomeType>

没有意义 - 如果 JavaScript 代码中的任何地方都不存在"AnotherString" ,您将无法获得它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM