【发布时间】:2018-08-21 22:38:57
【问题描述】:
我的项目中有许多以数字为参数的函数;这个数字一半时间是数组的索引,另一半时间是光标位置(数组中两个条目之间的点)。这会导致混淆,即使使用命名约定也是如此。
我想强制以下函数采用预期的名义类型。
class Index extends Number {}
class CursorPosition extends Number {}
function getElement(i: Index) {}
function getRange(p1: CursorPosition, p2: CursorPosition) {}
const myIndex: Index = 6;
const myPosition: CursorPosition = 6;
getElement(1); // would like this to fail at compile time
getRange(2, 3); // would like this to fail at compile time
getElement(myPosition); // would like this to fail at compile time
getRange(myIndex, myIndex); // would like this to fail at compile time
getElement(myIndex); // would like this to pass at compile time
getRange(myPosition, myPosition); // would like this to pass at compile time
我知道 typescript 使用结构化类型,这就是为什么这不会“开箱即用”发生。
另外,我考虑了对变量进行装箱和添加任意属性:
class myNum extends Number {
l: "1";
}
或使用演员表。
class myNum {
arb: "arbitrary property value";
}
const mn2: myNum = <any>8;
function getElement2(a: any[], i: myNum) {
return a[<any>i];
}
getElement2([], mn2);
getElement2([], 6);
有更好的想法吗?
【问题讨论】:
标签: typescript casting type-conversion