5

I want to assert the type of an objects property to clear an ambiguity that is caused by that property having a union type.

    interface myObject {
       myProperty: customType1|customType2    
    }
    //Now I want to make clear in some other line of code that i know what is
    // The type of that property at that time, somthing like this
    myObject.<customType1>myProperty

I searched around but I cant find anything referring to this kind of case, is it even possible?

4
  • 2
    It`s called a type guard and have a look at user-defined type guards as well, they are pretty nifty: typescriptlang.org/docs/handbook/… Commented Feb 5, 2019 at 18:27
  • It seems that type guards asks the type of the variable at runtime. is that right? Commented Feb 5, 2019 at 18:30
  • 1
    Also a discriminated union might be something else to look at in this context Commented Feb 5, 2019 at 18:31
  • Thanks for the suggestions but I need to tell TS what type I need, I dont need to check it at runtime, just like type assertion. The type of the object mostly depends on the parent object and not the object itself so discriminated union does not seem to apply here (sadly) Commented Feb 5, 2019 at 18:48

2 Answers 2

-1

It seems that the way of doing this is:

myObject.myProperty = myObject.myProperty as customType1

Thanks to the guys in the comments, I discovered a few interesting features today, but luckily what I needed ended up being quite simple.

Sign up to request clarification or add additional context in comments.

1 Comment

This is just type casting...
-2

As mentioned in the Typescript docs, https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types

First, assert type on the parent property and then access the child property

(<customType1>myObject.myProperty)
// or
(myObject.myProperty as customType1)

// if there is any child-property
(myObject.myProperty as customType1)['child_property_of_myproperty'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.