Home > OS >  How to make return type conditional on optional param
How to make return type conditional on optional param

Time:12-23

So I have a function like this

export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): ??? {
  const value = dict[key] as T | undefined;
  return value ?? fallback;
}

It would be nice that if I was calling myFunc that if the fallback was passed, it knew that undefined is no longer a possibility for the return type. For instance

const x = myFunc<boolean>({}, "hello") // should be typed as boolean | undefined

const y = myFunc<boolean>({}, "hello", false) // should be typed as boolean only but is typed as boolean | undefined

Right now, the return type is always T | undefined, even if I pass in a fallback. Is there a way to handle this conditional return type based on the presence of an optional param?

CodePudding user response:

This is function overloading. So we can define our 2 variants, 1 where fallback is defined and typed as T and another where fallback is specifically undefined. When defined we get back T and when undefined we get back T | undefined. And, once we do that, you should also be able to remove the as T cast as well.

export function myFunc<T>(dict: Record<string, T>, key: string, fallback: T):T;
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: undefined):T | undefined;
export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): T | undefined {
const value = dict[key] as T | undefined;
 return value ?? fallback;
}
  • Related