繁体   English   中英

TypeScript:如何使用rest参数返回函数中的条件类型?

[英]TypeScript: How to return conditional types in function with rest parameter?

我想用rest参数创建一个函数,它会返回这样的条件类型

  • 提供未定义的值时为null
  • 提供一个数字时的字符串
  • 提供多个数字的字符串数组

我试图使用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中重新创建的案例 - > 链接

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

  • unit(undefined) -> null
  • unit(16) -> string
  • 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;
}

你可以在这个游乐场看看。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM