有没有办法在 TypeScript 中创建扩展原始类型的名义类型? [英] Is there a way to create nominal types in TypeScript that extend primitive types?
问题描述
假设我正在跟踪两种类型的数字,例如 latitude
和 longitude
.我想用基本的 number
原语表示这些变量,但不允许在打字稿中将 longitude
分配给 latitude
变量.
Say I have two types of numbers that I'm tracking like latitude
and longitude
. I would like to represent these variables with the basic number
primitive, but disallow assignment of a longitude
to a latitude
variable in typescript.
有没有办法对 number
原语进行子类化,以便打字稿检测到这个分配是非法的?以某种方式强制名义输入以使此代码失败?
Is there a way to sub-class the number
primitive so that typescript detects this assignment as illegal? Someway to coerce nominal typing so that this code fails?
var longitude : LongitudeNumber = new LongitudeNumber();
var latitude : LatitudeNumber;
latitude = longitude; // <-- type failure
"如何在打字稿中扩展原始类型的答案?" 似乎它会让我朝着正确的方向发展,但我不确定如何扩展该解决方案来为不同的 种类的数字.
The answer to "How to extend a primitive type in typescript?" seems like it will put me in the right direction, but I am not sure how to extend that solution to create distinct nominal sub-types for different kinds of numbers.
我是否必须包装原语?如果是这样,我可以让它像普通数字一样无缝运行,还是必须引用子成员?我可以以某种方式创建一个打字稿编译时编号子类吗?
Do I have to wrapper the primitive? If so, can I make it behave somewhat seamlessly like a normal number or would I have to reference a sub-member? Can I just somehow create a typescript compile-time number subclass?
推荐答案
没有办法做到这一点.
在 GitHub 网站上跟踪此问题的建议是度量单位.
A suggestion tracking this on the GitHub site is Units of Measure.
在未来的版本中,您将能够使用 type
来定义原语的替代名称,但这些不会有任何与之关联的检查:
In a future release, you'll be able to use type
to define alternate names for the primitives, but these will not have any checking associated with them:
type lat = number;
type lon = number;
var x: lat = 43;
var y: lon = 48;
y = 'hello'; // error
x = y; // No error
这篇关于有没有办法在 TypeScript 中创建扩展原始类型的名义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!