gpt4 book ai didi

typescript - 想要强制一个特定类型的函数,但想要在 TypeScript 中有一个默认值

转载 作者:行者123 更新时间:2023-12-05 03:34:16 26 4
gpt4 key购买 nike

我想强制执行特定类型的函数,但希望某些函数具有默认值。

我尝试使用如下简单的代码

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

但它不起作用。

有什么办法可以解决吗?

最佳答案

A 和 B func 有不同的类型,不要强制它们成为同一类型:

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

关于typescript - 想要强制一个特定类型的函数,但想要在 TypeScript 中有一个默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70211293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com