Reputation: 270
I want to force a function of a specific type, but want to have a default value for some functions.
And I tried with simple code like below
type MyFunc = (str: string) => number;
const myAFunc: MyFunc = (str) => Number(str);
const myBFunc: MyFunc = (str = '9999') => Number(str);
myAFunc('a');
myAFunc(); // wants to occur error
myBFunc('b');
myBFunc(); // wants to NOT occur error
But it's not working.
Is there some way to solve it?
Upvotes: 3
Views: 361
Reputation: 485
If you want to make it optional to pass anything to the function, add a ? for parameter in the type.
type MyFunc = (str?: string) => number;
const myAFunc: MyFunc = (str) => Number(str);
const myBFunc: MyFunc = (str = '9999') => Number(str);
myAFunc(); // NaN
myBFunc(); // 9999
Upvotes: 0
Reputation: 714
A and B func has different types, don't force them into same type:
type MyAFunc = (str: string) => number;
type MyBFunc = (str?: string) => number;
const myAFunc: MyAFunc = (str) => Number(str);
const myBFunc: MyBFunc = (str = '9999') => Number(str);
myAFunc('a');
myAFunc(); // wants to occur error
myBFunc('b');
myBFunc(); // wants to NOT occur error
Upvotes: 3