我正在尝试使用泛型根据输入的特定形状缩小函数的返回类型。这在 TypeScript 中甚至可能吗?我有以下 MRE 证明了这个问题:
type ValidInput = {
filename: string;
sender: number;
};
type ValidInput2 = {
person: string;
sender: string;
};
type InferSenderType<T extends { sender: any }> = T extends { sender: infer K }
? K
: unknown;
type Api<I extends { sender: any }> = (input: I) => InferSenderType<I>;
declare const loadFile: Api<ValidInput | ValidInput2>;
const a = loadFile({ filename: "q", sender: 3 });
typeof a // string | number
// How do I get it to narrow the return type (in this case 'number') based on the input?