typescript - 使用泛型基于输入的窄返回类型
问题描述
我正在尝试使用泛型根据输入的特定形状来缩小函数的返回类型。这在 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?
解决方案
这是一个例子:
type ValidInput = {
filename: string;
sender: number;
};
type ValidInput2 = {
person: string;
sender: string;
};
type Api = <I extends { sender: any }>(input: I) => I['sender']
declare const loadFile: Api;
const a = loadFile({ filename: "q", sender: 3 });
typeof a // only number
推荐阅读
- java - 计算非二叉树的元素个数
- javascript - JavaScript - 设置超时功能,然后获取 innerHTML 并设置 sessionStorage
- numpy - numpy.rfftn 的多元多项式数组表示
- swift - 如何在完成处理程序中使用完成处理程序
- python - 通过查询集访问的对象没有 Django 中的属性
- vb.net - VB.net 使用验证执行插入语句时出现语法错误
- html - 放大镜和图像对齐
- git - .gitattributes 语言学家语言声明
- javascript - 遍历数组并加入 Google Apps 脚本
- python - AttributeError:“TensorSliceDataset”对象没有属性“get_shape”