Typescript 如何定义特定类型的常量?
如何定义空值构造函数(即特定类型的常量):Typescript 如何定义特定类型的常量?,typescript,union,constants,Typescript,Union,Constants,如何定义空值构造函数(即特定类型的常量): interface True {tag: "True"}; interface False {tag: "False"}; type Bool = True | False; const a = {tag: "True"}; // managed only that const a = True; // desired 也许你可以使用一个接口来代替使用接口。见 consttrue={tag:“True”}作为常量 const False={tag
interface True {tag: "True"};
interface False {tag: "False"};
type Bool = True | False;
const a = {tag: "True"}; // managed only that
const a = True; // desired
也许你可以使用一个接口来代替使用接口。见
consttrue={tag:“True”}作为常量
const False={tag:“False”}作为const;
类型Bool=typeof True | typeof False;//键入Bool={readonly标记:“True”}{readonly标记:“False”}
常数a=真;
console.log(a)/{tag:“True”}
您可以使用。见
consttrue={tag:“True”}作为常量
const False={tag:“False”}作为const;
类型Bool=typeof True | typeof False;//键入Bool={readonly标记:“True”}{readonly标记:“False”}
常数a=真;
console.log(a)/{tag:“True”}
是否希望TS中有const a=True
,并且它会发出const a={tag:“True”}代码>作为JavaScript?一般来说,静态类型系统是在TS编译为JS时使用的,因此运行时接口True
将不存在。您可以定义函数True():True{return{tag:“True”}
然后编写常量a=True()代码>。或者您可以用class True{readonly tag=“True”}
替换接口,然后编写const a=new True()代码>。这是我能想象的最接近的了。这两个对你有用吗?除非你有一个悬而未决的问题,否则我可以写一个答案。你可能在问什么?@VLAZ不,我希望True
是一个类型为Bool
@jcalz的常量值静态类型系统被删除了-这就是为什么我使用术语值构造函数而不是类型构造函数。因此TS只能定义显式空值构造函数,如function True():True{return{tag:“True”}
。谢谢您想让TS中的const a=True
发出const a={tag:“True”}代码>作为JavaScript?一般来说,静态类型系统是在TS编译为JS时使用的,因此运行时接口True
将不存在。您可以定义函数True():True{return{tag:“True”}
然后编写常量a=True()代码>。或者您可以用class True{readonly tag=“True”}
替换接口,然后编写const a=new True()代码>。这是我能想象的最接近的了。这两个对你有用吗?除非你有一个悬而未决的问题,否则我可以写一个答案。你可能在问什么?@VLAZ不,我希望True
是一个类型为Bool
@jcalz的常量值静态类型系统被删除了-这就是为什么我使用术语值构造函数而不是类型构造函数。因此TS只能定义显式空值构造函数,如function True():True{return{tag:“True”}
。谢谢看起来不错。不过我对TS不是很熟悉。这被认为是黑客攻击吗?我不认为这是黑客攻击,但这是一个奇怪的用法。不过我对TS不是很熟悉。这被认为是黑客攻击吗?我不认为这是黑客攻击,但这是一个奇怪的用例。