I want to make a function with rest parameter which will return conditional types like this:
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.