我的项目中有很多函数,它们以数字作为参数; 这个数字是数组索引的一半,另一半时间,它是一个光标位置(数组中两个条目之间的一个点).即使使用命名约定,这也会造成混淆.
我想强制执行以下功能正在采用预期的名义类型.
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 …
Run Code Online (Sandbox Code Playgroud)