Can I (somehow?) forbid the skipping of optional parameter in 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:
- If
head
isundefined
thentail
is alsoundefined
(and the list is empty)
Any TypeScript trick to achieve that? (This question is complementary to this question)
CodePudding user response:
You can use something called overloading. This works for both methods and functions in 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).
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'.