My goal here is to return a different type based on the presence of a optional condition: "CONDITION" parameter. And I'm trying to accomplish this without resorting to overloads.
type TYPE_1 = "TYPE_1"
type TYPE_2 = "TYPE_2"
type CONDITION = "CONDITION"
function foo(condition?: CONDITION): TYPE_1 | TYPE_2 {
if (condition) {
return "TYPE_1";
}
else {
return "TYPE_2";
}
}
const shouldBeType_1 = foo("CONDITION"); // ERROR: THIS IS BEING EVALUATED AS UNION TYPE: "TYPE_1" | "TYPE_2"
const shouldBeType_2 = foo(); // ERROR: THIS IS BEING EVALUATED AS UNION TYPE: "TYPE_1" | "TYPE_2"
This is easy to accomplish with overloads:
/* ########################################### */
/* #### THIS IS EASY TO DO WITH OVERLOADS #### */
/* ########################################### */
function foo_overloaded(): TYPE_2
function foo_overloaded(condition: "CONDITION"): TYPE_1
function foo_overloaded(condition?: "CONDITION"): TYPE_1 | TYPE_2 {
if (condition) {
return "TYPE_1";
}
else {
return "TYPE_2";
}
}
const overloaded_shouldBeType_1 = foo_overloaded("CONDITION"); // SUCCESS: THIS IS TYPE_1
const overloaded_shouldBeType_2 = foo_overloaded(); // SUCCESS: THIS IS TYPE_2
What is the proper way of doing it without overloads? Or am I over complicating it and overloading is simply the way to go in this situation?
Also there is this question here on SO: TypeScript: function return type based on argument, without overloading
It suggests that an interface should be used as a map to the return type, like:
interface Registry {
A: number,
B: string,
C: boolean
}
function createType<K extends keyof Registry>(type: K, value: Registry[K]): Registry[K] {
return value;
}
But I can't do that, because condition is either "CONDITION" | undefined. So how can I map the undefined type? I also tried doing that with conditional type. Something like:
type RETURN_TYPE<T extends undefined | "CONDITION"> = T extends "CONDITION" ? TYPE_1 : TYPE_2;
But that didn't work either.