为了避免将我输入的所有变量相互混淆,我想通过键入它们来添加额外的安全层,如果我试图将文字数字或另一种类型赋给这个新类型,就会产生编译错误.
你可以把它看作给我的变量一个单位,例如"秒"和"米".它们都是从文字类型"Numbers"派生的,但是我应该不能用一个类型的Meter添加一个变量类型的Second.我也不应该能够将类型为Second的变量赋给另一个类型为Meter的变量.
let length1 = 5 as Meter;
let length2 = 7 as Meter;
let duration1 = 10 as Second;
let duration2 = 11 as Second;
let lengthSum = length1 + length2 // should type lengthSum as Meter and give it a value of 12
let durationSum = duration1 + duration2 // should type durationSum as Second and give it a value of 21
length1 = duration2 // should generate an error
let foo = length1 + duration1; // should generate an error
通过扩展,我也想对字符串执行同样的操作:
let myBookTitle = "Best title ever" as Title;
let myBookAuthor = "John Doe" as Author;
myBookTitle = myBookAuthor // should generate an error
.
我try 了以下自定义类型:
type Meter = number & { __type: 'meter' };
type Second = number & { __type: 'second' };
它们适用于大多数情况,但忽略了混合加法的情况:
let length1 = 5 as Meter;
let length2 = 10 as Meter;
let duration1 = 2 as Second;
let duration2 = 3 as Second;
length1 = length2; // works as expected
length1 = duration1; // generates an error as expected
let length10 = (length1 + length2) as Meter; // works but is not able to automatically infer the length10 type with the "as Meter"
let length11 = (duration1 + duration2) as Second; //same as above
let length12 = (length1 + duration2) as Second; // Shouldn't allow such addition but does it without any error!!
Would anyone know how to create a new type that covers all my constraints? (I know there are some npm packages that cover specifically the SI units, but that is not what I am looking for. Units are used here as examples; I will need to handle multiple types of différents types outside "simple" units. Thanks.)