pavels555
pavels555
TTCTheo's Typesafe Cult
Created by pavels555 on 7/11/2024 in #questions
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;
3 replies