#Can you mutate an object's type based on one of its properties?

8 messages · Page 1 of 1 (latest)

buoyant leaf
#

Take, for example, an interface or type alias describing a websocket message:

interface WSMessage {
  type: 'msg_x' | 'msg_y' | 'msg_z'
  x_prop?: string;
  y_prop?: string;
  z_prop?: string;
}

Can you dynamically cast something like const data = JSON.parse(event.data) as WSMessage;
based on the value of its type property? And thus ensure whether you're dealing with a WSMessage that has the matching property?

Assume I've got an interface that describes each variety with type containing a single possibility and only the appropriate property as well.
Thank you for your time!

dull acorn
#

Can you dynamically cast something like const data = JSON.parse(event.data) as WSMessage; based on the value of its type property?
this indicates a fundamental misunderstanding of what typescript is. everything that typescript does happens statically at compile-time. at runtime you just have regular javascript. so the answer is most definitely "no"

buoyant leaf
#

Aye this is exactly what I was attempting to achieve. Thanks. And I suppose 'dynamically' wasn't the right term, but the 'fundamental misunderstanding' bit is unhelpful. Regardless, I appreciate your time and response, friend 🙂

dull acorn
#

a lot of people coming from languages like C# where types exist at runtime come into TS with this same exact misunderstanding

buoyant leaf
#

yeah, i see what youre saying. and i for sure appreciate your pointing me to the discriminated unions.

the silly thing is i was just reading thru the TS docs so I could find the right syntax format for describing methods in an interface, and i read right through the whole discriminated unions section and it didn't click in my head that that was what i was looking for. i just had the feeling when i was thinking about how to solve my problem that i knew it was possible but i couldn't remember how, or blunder my way through to the answer xD

#

But as we can see, it solved exactly what I was trying to fix