I am struggling to implement type checking on the payload
argument of the notify
method in the following class. Here is the code I have tried:
type UserNotificationTypes = {
ASSIGNED_TO_USER: {
assignedUserId: string
}
MAIL_MESSAGE_SENT: {
receiverUserId: string
}
}
export class UserNotificationService {
notify: <TypeKey extends keyof UserNotificationTypes>(type: TypeKey, payload: UserNotificationTypes[TypeKey]) => void = (
type,
payload,
) => {
if (type === 'ASSIGNED_TO_USER') {
const a = payload.assignedUserId
}
if (type === 'MAIL_MESSAGE_SENT') {
const b = payload.receiverUserId
}
}
}
When using TypeScript, an error is displayed:
Property 'assignedUserId' does not exist on type '{ assignedUserId: string; } | { receiverUserId: string; }'. Property 'assignedUserId' does not exist on type '{ receiverUserId: string; }'.