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

时间:2019-05-29 10:18:24

标签: typescript conditional-types

我想创建一个带有rest参数的函数,该函数将返回条件类型,如下所示:

  • (提供未定义的值
  • 时)
  • 字符串(如果提供一个数字
  • 字符串数组(如果提供多个数字

我正尝试使用TypeScript 扩展语法以多种形式编写此函数,但不幸的是,这些都不起作用。

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

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

import { rem } from "polished";

type UnitValue = number | undefined;

const unit = (...values: UnitValue[]): string | string[] | null => {
  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;
};

codesansbox.io -> link

中重新创建的案例

在以下三种情况下,我需要此函数才能精确返回并且仅这些类型:

  • unit(undefined) -> null
  • unit(16) -> string
  • unit(16, 32) -> string[]

1 个答案:

答案 0 :(得分:3)

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

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;
}

您可以在this playground中签出。

相关问题