Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading