我试图输入一个接受字符串或string []并分别返回bool或bool []的函数。我已经尝试过使用泛型类型和重载,但似乎都抛出某种错误:
// generic way
function genericWay<T extends string | string[]>(val: T): T extends string ? boolean : boolean[] {
if (typeof val === 'string'){
return true // Type 'true' is not assignable to type 'T extends string ? boolean : boolean[]'
}
return [true] // Type 'true[]' is not assignable to type 'T extends string ? boolean : boolean[]'
}
const a1 = overloadWay('bbb')
const a2 = genericWay(['bbb'])
const a3 = genericWay(5333) // should throw error
// overload way
function overloadWay(val: string[]): boolean[]; // This overload signature is not compatible with its implementation signature.
function overloadWay(val: string): boolean {
if (typeof val === 'string'){
return true
}
return [true] // Type 'boolean[]' is not assignable to type 'boolean'.
}
const b1 = overloadWay('bbb')
const b2 = overloadWay(['bbb'])
const b3 = overloadWay(5333) // should throw error
由于另一个答案已经提供了如何以通用方式解决警告,这需要显式的类型转换,因此您可以使用函数重载来达到相同的目标。
您的重载方式定义不正确。您需要先指定所有重载,然后函数和实现函数应在其签名中包含所有可能的输入和输出。您可以any
在实现中求助,但我认为无论如何都可以避免这样做。
这是过载的方式
// overload way
function overloadWay(val: string[]): boolean[];
function overloadWay(val: string): boolean ;
function overloadWay(val: string| string[]): boolean | boolean[] {
if (typeof val === 'string'){
return true
}
return [true]
}
// b1 is boolean
const b1 = overloadWay('bbb')
// b2 is boolean[]
const b2 = overloadWay(['bbb'])
// shows error
const b3 = overloadWay(5333)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句