“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.

- First of all, define commonly used
Chattype.
export interface ChatCommon<T extends MessageType = MessageType.Message> {
id: string;
sender: User;
messageType: T;
created?: Date;
updated?: Date;
}- The
defaultMessageType isMessageType.MessageandChatCommonis used when no generic type is defined. messageTypecan be assigned in agenerictype variable.
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;
}
- Each different message type passes its generic type to
ChatCommon.
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>;ChatPropscan have a specific type depending on conditions.
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.


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🎉
