Typescript – assure that return of function is of given type

Issue

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

Solution

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

Answered By – Pyxel Codes

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published