[英]Forbid skipping optional parameter with undefined
Can I (somehow?) forbid the skipping of optional parameter in typescript?我可以(以某种方式吗?)禁止跳过 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
I want to statically enforce the following property on my list:我想在我的列表中静态强制执行以下属性:
head
is undefined
then tail
is also undefined
(and the list is empty)head
undefined
则tail
也undefined
(并且列表为空) Any TypeScript trick to achieve that?任何 TypeScript 技巧可以实现吗? (This question is complementary to this question )
(这个问题是对这个问题的补充)
You can use something called overloading .您可以使用称为重载的东西。 This works for both methods and functions in TS.
这适用于 TS 中的方法和函数。 The basic idea is that you have single function/method implementation with all the possible arguments and you can specify different combintations of the function's arguments (just like for your case where you can have 0 arguments, only the first or both).
基本思想是你有单一的函数/方法实现所有可能的 arguments 并且你可以指定函数的arguments的不同组合(就像你的情况你可以有 0 arguments,只有第一个或两个)。
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'.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.