Bishonen_PL
Bishonen_PL

Reputation: 1571

Typescript - assure that return of function is of given type

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

Upvotes: 0

Views: 430

Answers (2)

ejose19
ejose19

Reputation: 599

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.

Upvotes: 0

Pyxel Codes
Pyxel Codes

Reputation: 170

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

Upvotes: 1

Related Questions