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



我在提供默认回调值和跟踪该回调的返回类型时遇到了麻烦

在下面的情况中,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

游乐场

最新更新