J. Hesters
J. Hesters

Reputation: 14806

How to assign a type to an object in TypeScript based on switch case

I'm building a React Native app with TypeScript.

I'm writing a handler with a switch case like this:

export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => {
  const { type, message_data } = messageData;
  const data = camelizeKeys(JSON.parse(message_data));
    switch (type) {
        case conditionOne:
          data.consumer = data.consumer.uuid;
          setHouses({ entities: { houses: { [data.uuid]: data } } });
        // ... more cases
        default:
          // ... do stuff
      }
    };

In each case I know of which type data is. How can I tell typescript that?

Pseudo code:

case conditionOne:
  data: MyType;
  data.consumer = data.consumer.uuid;

Upvotes: 0

Views: 849

Answers (1)

bcherny
bcherny

Reputation: 3172

More code around your switch would be helpful (eg. where do type and data come from, and what do they look like?). In general, you can use a tagged union, object type, record type, or a number of other ways to declare a relationship between two types.

Upvotes: 1

Related Questions