Can I check type for union type in typescript?

Is there a way to make an “instanceof” -like request for an object against a union type built into the language?

I have a type alias with a union type as follows:

type MyType = Foo | Bar | Thing; 

Each of Foo , Bar and Thing inherits from Base

 class Base { /* ... */ } class Foo extends Base { /* ... */ } class Bar extends Base { /* ... */ } class Thing extends Base { /* ... */ } 

Some methods return Base .

 function getBase(): Base { /* ... */ return base; } 

Ideally, I would like to create another method that can return MyType after calling getBase()

 function getMyType(): MyType { var item = getBase(); if (item instanceof MyType) return item; else return null; } 

If MyType were not a type alias, the above code will work. However, since it is a type alias, it does not seem to work. So, to repeat my question, does any of this fit into the language?

Clearly, what I want can be done by checking the instance of the request for each individual class:

 function getMyType(): MyType { var item = getBase(); if (item instanceof Foo || item instanceof Bar || item instanceof Thing) return item; else return null; } 

But this is hardly ideal; if some future developer wanted to create OtherThing and extend MyType to include this new class, then I hope they remembered the getMyType() update.

Is there a function built into the language to solve this problem, or is there a potentially better way to do this?

+5
source share
1 answer

There is no representation of type aliases at runtime, so nothing is “built-in” to perform this kind of validation.

This template would be fully supported, though:

 // Future devs: Please keep these in sync type MyType = Foo|Bar|Thing; let MyTypeClasses = [Foo,Bar,Thing]; function getMyType(): MyType { var item = getBase(); if (MyTypeClasses.some(c => item instanceof c)) return item; else return null; } 
+3
source

Source: https://habr.com/ru/post/1234637/


All Articles