typescript - 使用泛型基于输入的窄返回类型

标签 typescript typescript-generics

我正在尝试使用泛型根据输入的特定形状缩小函数的返回类型。这在 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 

TS Playground

关于typescript - 使用泛型基于输入的窄返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66205700/

相关文章:

javascript 使用浏览器时区解析日期字符串

TypeScript 泛型 - 期望类型参数是枚举,并引用它的键

带有函数参数的 typescript 泛型

Typescript键值关系保留Object.entries类型

angularjs - Liferay7.0 portlet build with angular and typescript

javascript - 具有现有验证的 Angular 控制值访问器

javascript - 将多个可观察量的结果处理到数据库并添加到数据库一次

typescript - 为什么 Webpack 5 包含我未使用的 TypeScript 枚举导出,即使启用了 Tree Shaking?

typescript - 如何推断具有多个泛型的 Typescript 可变参数元组类型?

typescript - 如何获得 TypeScript 映射类型的逆?