TypeScript:如何在带有rest参数的函数中返回条件类型?

TypeScript:如何在带有rest参数的函数中返回条件类型?,typescript,conditional-types,Typescript,Conditional Types,我想用rest参数创建一个函数,它将返回条件类型,如下所示: import { rem } from "polished"; function unit(...values: undefined[]): null; function unit(...values: [number]): string; function unit(...values: number[]): string[]; function unit(...values): null | string | string[]

我想用rest参数创建一个函数,它将返回条件类型,如下所示:

import { rem } from "polished";

function unit(...values: undefined[]): null;
function unit(...values: [number]): string;
function unit(...values: number[]): string[];
function unit(...values): null | string | string[] {
  const result: string[] = [];

  values.forEach(value => {
    if (value) {
      result.push(rem(value));
    }
  });

  if (result.length === 1) {
    return result[0];
  }

  if (result.length > 1) {
    return result;
  }

  return null;
}
  • null当提供未定义的值时
  • 字符串当提供一个数字时
  • 字符串数组当提供多个数字时
我试图用TypeScriptextends语法以多种形式编写此函数,但不幸的是,所有这些都不起作用

我还试图编写函数,其中第一个参数是数字,第二个是rest参数,但它也不起作用

这就是当前工作代码的外观,除了正确的条件返回类型外:

从“抛光”导入{rem};
类型UnitValue=编号|未定义;
常量单位=(…值:单位值[]):字符串|字符串[]| null=>{
常量结果:字符串[]=[];
values.forEach(值=>{
如果(值){
结果:推(rem(值));
}
});
如果(result.length==1){
返回结果[0];
}
如果(result.length>1){
返回结果;
}
返回null;
};
在codesansbox.io中重新创建的案例->

在这三种情况下,我需要此函数准确且仅返回这些类型:

  • 单位(未定义)->null
  • 单元(16)->字符串
  • unit(16,32)->string[]

您可以通过使用来实现此行为。 您的代码如下所示:

import { rem } from "polished";

function unit(...values: undefined[]): null;
function unit(...values: [number]): string;
function unit(...values: number[]): string[];
function unit(...values): null | string | string[] {
  const result: string[] = [];

  values.forEach(value => {
    if (value) {
      result.push(rem(value));
    }
  });

  if (result.length === 1) {
    return result[0];
  }

  if (result.length > 1) {
    return result;
  }

  return null;
}
你可以登记入住