Conditional typing using typescript generic

dooboolab
dooboolab
Nov 3 · 2 min read

“In this post, I’d like to write about some of the problems and solutions that have emerged in the context of complementing typescript typing during HackaTalk development.”

enum MessageType {
Message,
Photo,
}
export interface Chat {
id: string;
sender: User;
messageType: MessageType;
message?: string;
photo?: string;
created?: Date;
updated?: Date;
}

I saw that the Chat types are written in typescript as above and needed to improve, so I sent the PR. As you can see, the chat MessageType has the chance to expand with more categories and the contents of the message will vary depending on the MessageType. There may be a photo or message, but depending on the type, they may not coexist. In the current state, it is assumed that there is only message in MessageType.Mesage and photo is only in MessageType.Photo.

To loosely define typing, you can just give message? and photo? as shown above. However, someone may feel indifferent on how you code.

I will complement that now.

export interface ChatCommon<T extends MessageType = MessageType.Message> {
id: string;
sender: User;
messageType: T;
created?: Date;
updated?: Date;
}

2. Let’s extend each of them and define an interface.

interface Message<MessageType.Message> extends ChatCommon<T> {
message: string;
}
interface Photo<MessageType.Message> extends ChatCommon<T> {
photo: string;
}

3. Group multiple message types with conditional typing technique in typescript.

export type ChatProps<T extends MessageType = MessageType.Message>
= T extends MessageType.Message
? Message<T>
: T extends MessageType.Photo
? Photo<T>
: ChatCommon<T>;

4. In order to have a variable of type Chat comprehensively in an array, the following types are specified.

type ChatType = MessageType.Message | MessageType.Photo;

5. Finally, I did the following.

export type Chat = ChatProps<ChatType>;

The result is as shown.

When messageType is `Photo`, message doesn’t exist.
When messageType is `Message`, the message exists.

I think we can solve the above problem in a better way. This was just my runway solution. It’s always welcomed if you can supplement your PR🎉

dooboolab

Open source community

dooboolab

Written by

dooboolab

dooboolab

dooboolab

Open source community

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade