0

I have an interface that extends multiple interfaces

interface A extends B, C { a1: type; a2: type; a3: type; } interface B { b1: type; b2: type; b3: type; } interface C { c1: type; c2: type; c3: type; } 

The server responses with A and I have separate objects of type B and C. What I want to do is decouple it using Types so that I won't have to do

a:A = response b = { b1: a.b1, b2: a.b2 ... } c = { c1: a.c1, c2: a.c2 ... } 

1 Answer 1

3

You can simply use an assert type

If you do something like

returnedObject as B 

This will basically extract the B part of the object as long as it’s compliant. Meaning it needs to have all the properties defined in the B contract. And this is true for C also if you do

returnedObject as C 

Basically type assertion is a kind of casting but in compile time. Not on runtime like a regular casting.

You are telling TypeScript that you have total control on the object type being returned and you know exactly the format of what’s being returned.

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

2 Comments

Yes, there is no such thing as runtime casting since there are no types in JavaScript
Handles assertion. But in this way, it does type assertion but not extraction of specific keys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.