If I have the code snippet below, how can I properly define the data object type based on the known value of data.type?
In this scenario, I aim to assign a specific type to data
when its type
property is either "sms" or "email"
const payload = '{"type":"sms","destination":123}'
type PayloadType = 'sms' | 'email'
interface BasePayload {
type: PayloadType
}
interface SmsPayload extends BasePayload {
destination: number
}
interface EmailPayload extends BasePayload {
destination: string
}
const data: SmsPayload | EmailPayload = JSON.parse(payload)
Thanks in advance!
*PS: I am aware that phone numbers are not actual numbers... this is purely for demonstration purposes.