Is it possible to define a type that resolves to one of two given types?

Assuming I have several functions that return the same number | Date type is it possible to define a type that will be one of these two?

I.e. instead of:

foo1(): number | Date {}
foo2(): number | Date {}

is it possible to have:

foo1(): NumberOrDate {}
foo2(): NumberOrDate {}

?

Or is there any other idea on how to stay DRY and not repeat number | Date?

>Solution :

You can just declare a type alias for the union:

type NumberOrDate = number | Date

function foo1(): NumberOrDate { return 1;}
function foo2(): NumberOrDate { return new Date}

Playground Link

Leave a Reply