gpt4 book ai didi

typescript - 定义 TypeScript 回调类型并提供默认回调值

转载 作者:行者123 更新时间:2023-12-04 07:59:39 32 4
gpt4 key购买 nike

我在提供默认回调值和跟踪该回调的返回类型时遇到问题
在以下情况下,ab两者都有类型 any但我希望它们具有任何 callback 的返回类型返回。在这种情况下 stringnumber但原则上,它可以是任何东西

const defaultCallback = () => 'Hello World'

function main(callback: () => any = defaultCallback){
return callback()
}

const a = main(() => 'Foo') <-- Type is any but should be string
const b = main(() => 1000) <-- Type is any but should be number
const c = main() <-- Type is any but should be string
所以为了解决这个问题,我尝试了很多方法,包括以下列方式引入泛型。除了我似乎无法再提供默认值之外,此定义可以正常工作。
const defaultCallback = () => 'Hello World'

function main<T extends any>(callback: () => T = defaultCallback): T {
return callback()
}

const a = main(() => 'Hello World') <--- Type string
const b = main(() => 1000) <--- Type number
const c = main() <-- Should be acceptable which requires a default value for callback
上面的代码在没有 defaultCallback 的情况下工作但与 defaultCallback我收到: Type '() => string' is not assignable to type '() => T'. Type 'string' is not assignable to type 'T'. 'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'unknown'.(2322)

最佳答案

您可以在重载的帮助下实现它:

const defaultCallback = () => 'Hello World'

function main<R>(callback: () => R): R
function main(): ReturnType<typeof defaultCallback>
function main(callback = defaultCallback) {
return callback()
}

const a = main(() => 'Foo') // string
const b = main(() => 1000) // number
const c = main() // string
Playground

关于typescript - 定义 TypeScript 回调类型并提供默认回调值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66537120/

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