我正在尝试键入一个接受字符串或字符串[] 并分别返回 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)
关于typescript - 根据参数区分返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65896206/