Given the following code, how would I define the type of object data
when data.type
is a known value?
In the below example, I would like data
to be typed accordingly when data.type
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)
TIA
*PS: I know phone numbers aren't numbers... this is just an example.
It's hard to leave inheritance behind sometimes, but here it isn't necessary.
Just create two types with a common discriminating field, type
:
interface SmsPayload {
type: 'sms'
destination: number
}
interface EmailPayload {
type: 'email'
destination: string
}
create a union type from these:
type PayloadUnion = EmailPayload | SmsPayload
now, you can:
const data: PayloadUnion = JSON.parse(payload) // trusting the backend here
and narrow using the common discriminator field
if (data.type === 'sms'){
// in here `data` is of type SmsPayload
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments