【问题标题】:Narrow return type based on input using generics使用泛型基于输入的窄返回类型
【发布时间】:2021-02-15 17:57:44
【问题描述】:

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

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    这是一个例子:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 2016-10-16
      • 2023-03-30
      • 1970-01-01
      • 2020-05-02
      相关资源
      最近更新 更多