Home > Net >  How to type return value as boolean|typeof param
How to type return value as boolean|typeof param

Time:12-28

Given

function toBool(str: string|boolean|number|any[], def:any=undefined): boolean|typeof def {
    return true;
}

const x = toBool('true',false);

Mousing over x shows its of type any. But in this scenario, it should be a boolean because I've specified def.

Likewise, if I do

const y = toBool('true','fallback');  // y should be boolean|string (or boolean|"fallback" would also be fine)
const z = toBool('true');  // z should be boolean|undefined

TS playground

How can I achieve this?

I've also tried this:

function toBool<TDefault>(str: string|boolean|number|any[], def:TDefault=undefined): boolean|TDefault

But that gives an error,

Type 'undefined' is not assignable to type 'TDefault'. 'TDefault' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.

CodePudding user response:

You can use a generic T with a default type of undefined, and make the default value an optional parameter:

TS Playground

function toBool <T = undefined>(
  value: string | boolean | number | any[],
  defaultValue?: T,
): boolean | T {
  return true;
}

const x = toBool('true', false); // boolean
const y = toBool('true','fallback'); // boolean | "fallback"
const z = toBool('true'); // boolean | undefined
  • Related