Since another answer already provides with how to fix the warning in the generic way, which requires explicit type casting, here is how you can use function overloading to achive the same goals.
Your overload way definition is not correct. You need to specify all the overloads before the function and the implementing function should contain all the possible inputs and outputs in its signature. You may resort to any
in the implementation, but I do not think that's advisable wherever you can avoid.
Here is the overload way
// 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)
TS Playground
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…