简体   繁体   中英

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

I want to make a function with rest parameter which will return conditional types like this:

  • null when provided undefined value
  • string when provided one number
  • array of strings when provided multiple numbers

I was trying to write this function in multiple forms using TypeScript extends syntax but unfortunately none of these was working.

I was also trying to write function where first parameter was a number and the second one was rest parameter but it also didn't work.

This is how working code looks right now except of proper conditional return of types:

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

Recreated case in codesansbox.io -> link

I need this function to return exactly and only these types in those three cases:

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

You can achieve this behavior by using function overloads . Your code will look like this:

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

You can check out in this playground .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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