【发布时间】:2022-01-23 21:56:49
【问题描述】:
所以我有这样的功能
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): ??? {
const value = dict[key] as T | undefined;
return value ?? fallback;
}
如果我调用 myFunc 并且如果通过了回退,那就太好了,它知道 undefined 不再是返回类型的可能性。比如
const x = myFunc<boolean>({}, "hello") // should be typed as boolean | undefined
const y = myFunc<boolean>({}, "hello", false) // should be typed as boolean only but is typed as boolean | undefined
现在,返回类型总是 T |未定义,即使我通过后备。有没有办法根据可选参数的存在来处理这种条件返回类型?
【问题讨论】:
标签: typescript typescript-typings typescript-generics