Home > Software engineering >  Typescript - assure that return of function is of given type
Typescript - assure that return of function is of given type

Time:11-13

Having a simple function which accepts some variable, how can we let TS know that the output will ALWAYS satisfy the type of some variable and thus it shouldn't yell about

Type 'string | Date' is not assignable to type?

I.e.

const getStringOrDate(asString = true) => {
    if (asString) {
       return new Date().toLocaleDateString()
    } else {
        return new Date()
    }
  }


const today: Date = getStringOrDate(false);
^  Type 'string | Date' is not assignable to type Date

CodePudding user response:

you can define the function multiple times with different types

and assign different return types, you define a return type by appending it after the brackets, for example let fn = (): number => 1;

using this you can just use this

function getStringOrDate(asString?: true = true): string;
function getStringOrDate(asString?: false = true): Date;
function getStringOrDate(asString = true): Date | string {
    return asString ? new Date().toLocaleString() : new Date();
}

Note that this only works with the function keyword, not es5 arrow functions

this would set the return type to string or Date correctly

CodePudding user response:

Besides multiple function implementation (which should be preferred), you could also use a conditional return type, it looks like this:

function getStringOrDate<T extends boolean = true>(
  asString = true as T
): T extends true | undefined ? string : Date {
  return (asString ? new Date().toLocaleDateString() : new Date()) as any;
}

the downside of this method is the need to use casting, however implementations of this kind may be more idiomatic very specific cases.

  • Related