举例如下:
const resultIs = (input: any, target?: any) => {
let result: any = ...;
// ...
// 对input的处理
if (target) {
return result === target;
}
return resultIs;
}
假如我要对input进行处理,处理得到的结果是result,如果传了期望值target,则返回一个boolean值,表示result是不是符合期望的值target,如果没传target,则直接返回result
问题:怎么定义resultIs的参数和返回类型,才能明确如果target传了,返回的值固定为boolean类型,如果没有传,则input为什么类型,result即为什么类型?
=============================更新============================
以实际例子说吧:
type AllType = 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | 'array' | 'null' | 'nan'
const typeIs = <M>(input: M, target?: AllType): boolean | AllType => {
if (Array.isArray(input)) {
return !target ? 'array' : target === 'array';
} else if (input === null) {
return !target ? 'null' : target === 'null';
} else if (typeof input === 'number' && isNaN(input)) {
return !target ? 'nan' : target === 'nan';
}
return !target ? typeof input : target === typeof input;
}
const aa = 'asdsad';
typeIs(aa, 'string')
typeIs(aa)