Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wants to force a function of a specific type, but want to have a default value in TypeScript

Tags:

typescript

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

https://www.typescriptlang.org/play?#code/C4TwDgpgBAsiBiBXAdgYygXigCgM7ACcAuKfAgS2QHMBKTAPimUQFsAjCAgbgCgfUA9snxQWIAIJI0JOFPRY8hOhkYA5VhwKKCNXoOHBRIAEJyZCFPJxlMUAOQBOJw7vK1Gztt18xky9jsAQ1deXzlsXSgAeiioAHdA5GBcKGABKAFUVEQCKE4CAQIeMVN-OzYQ4pNwyJj4xOTU9NUAeQAVDKycvIICgiA

But it's not working.

Is there some way to solve it?

like image 518
grace Avatar asked Nov 20 '25 20:11

grace


1 Answers

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
like image 88
gaborp Avatar answered Nov 22 '25 15:11

gaborp