禁止跳过未定义的可选参数



我能(以某种方式)禁止在typescript中跳过可选参数吗?

class MyList {
constructor(
public head?: number,
public tail?: MyList
){}
}
const L0 = new MyList();              // <--- empty element list - good !
const L1 = new MyList(888);           // <--- single element list - good !
const L2 = new MyList(777, L0);       // <--- general list - good !
const L3 = new MyList(undefined, L1); // <--- forbid this 

我想静态地在我的列表中强制执行以下属性:

  • 如果headundefinedtail也为undefined(且列表为空)

有什么TypeScript技巧可以实现吗?(这个问题是这个问题的补充)

你可以使用重载。这对TS中的方法和函数都有效,基本的思想是你有一个单一的函数/方法实现和所有可能的参数,你可以指定函数参数的不同组合(就像你可以有0个参数的情况,只有第一个或两个)。

class MyList {
constructor()
constructor(head: number)
constructor(head: number, tail: MyList)
constructor(
public head?: number,
public tail?: MyList
){}
}
const L0 = new MyList(888);
const L1 = new MyList(777, L0);   
const L2 = new MyList(undefined, L1); // This will show error: Argument of type 'undefined' is not assignable to parameter of type 'number'.

最新更新