【问题标题】:array and conditional recursive types for a rest parameter in typescript 4.1typescript 4.1中rest参数的数组和条件递归类型
【发布时间】:2023-03-28 22:14:01
【问题描述】:

我想使用条件类型作为休息参数,但当我第一次进行测试时我很惊讶

这是playground,这是代码:

type ExtractParts<P extends any[]> =
    P extends [infer H, ...infer U]
      ? ['yes way']
      : ['no way']


interface A {
  description: string;
  action: () => {
      say: string;
      it: string;
  };
}

type Q = ExtractParts<[1,2,3]> // ['yes]
type P = ExtractParts<A[]>; // ['no way']

type R = ExtractParts<[{    // ['yes way']
  description: string;
  action: () => {
      say: string;
      it: string;
  };
}]>;

我对这种行为感到惊讶

type P = ExtractParts<A[]>; // ['no way']

但这正如我所想,因为它是一个严格的元组

type R = ExtractParts<[{    // ['yes way']
  description: string;
  action: () => {
      say: string;
      it: string;
  };
}]>;

我想将此技术与休息参数一起使用

type ExtractParts<P extends any[]> =
    P extends [infer H, ...infer U]
      ? ['yes way']
      : ['no way']


function parts<P extends any[]>(...parts: ExtractParts<P>){}

const b = parts(1,2,3);

但是P extends [infer H, ...infer U] 返回 false

我可以使用这样的条件类型来推断休息参数的头部和尾部吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    问题在于数组可以有 0 个元素,而元组 [H, ...T] 必须至少有一个元素。您可以使用可选的第一个元素 [H?, ...T] 定义一个元组,这将是一个数组的基本类型。

    所以在条件类型中你会使用[(infer H)?, ...infer U]

    type ExtractParts<P extends any[]> =
        P extends [(infer H)?, ...infer U]
          ? ['yes way']
          : ['no way']
    
    
    interface A {
      description: string;
      action: () => {
          say: string;
          it: string;
      };
    }
    
    
    type Q = ExtractParts<[1,2,3]> // ['yes way']
    type P = ExtractParts<A[]>; // ['yes way']
    
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2020-02-06
      相关资源
      最近更新 更多