Types union and how to distinguish them?

doing so I can check later if kind === EventType.Click, and typescript will know that inside that block the object is ClickEvent. Is that a good approach to this? Also, could I use instead of kind: 'click'; the actual type value? EventType.Click ? What do you think of enums? Should I have created it as enums instaed of const object? Thanks alot!
type BaseEvent = {
id: string;
name: string;
kind: EventType;
createdBy?: string;
updatedBy?: string;
createdAt?: string;
updatedAt?: string;
};

export const EventType = {
Click: 'click',
Tap: 'tap',
} as const;

export type EventType = (typeof EventType)[keyof typeof EventType];

export type ClickEvent = BaseEvent & {
kind: 'click';
definition: string;
};

export type TapEvent = BaseEvent & {
kind: 'tap';
optional?: string;
};

export type UnifiedEvent = ClickEvent | TapEvent;
type BaseEvent = {
id: string;
name: string;
kind: EventType;
createdBy?: string;
updatedBy?: string;
createdAt?: string;
updatedAt?: string;
};

export const EventType = {
Click: 'click',
Tap: 'tap',
} as const;

export type EventType = (typeof EventType)[keyof typeof EventType];

export type ClickEvent = BaseEvent & {
kind: 'click';
definition: string;
};

export type TapEvent = BaseEvent & {
kind: 'tap';
optional?: string;
};

export type UnifiedEvent = ClickEvent | TapEvent;
1 Reply
tylerlaws0n
tylerlaws0n5mo ago
I think your code is completely fine. If you’re interested in learning more for when/why to use enums… this is a fantastic post on optimizing JavaScript that includes a good section about string comparisons vs enums https://romgrk.com/posts/optimizing-javascript For your use case I can’t imaging it mattering without this event being checked tons of times, but still worth understanding the trade offs and when it matter I think.
Want results from more Discord servers?
Add your server