TypeScript Function Conditional Type Good Usage

Example 1

type MessageOf<T> = T extends { message: infer MessageType } ? MessageType : never;

const getMessage = <T extends { message: any }>(obj: T): MessageOf<T> => obj.message;



const sms = { phone: '07733838', message: ['Hello World', 'Merhaba Dunya'] };

const smsMessage = getMessage(sms); // string[]

const email = { from: 'kh@kh.com', to: 'kkkk@kkkk.com', message: 'Hello World' };

const emailMessage = getMessage(email); // string

Example 1.1

Notice that line 3 in below code, T extends { message: unknown } message field data type is unknown so returning value from function should be casted to any like obj.message as any

type MessageOf<T> = T extends { message: infer MessageType } ? MessageType : never;

const getMessage = <T extends { message: unknown }>(obj: T): MessageOf<T> => obj.message as any;



const sms = { phone: '07733838', message: ['Hello World', 'Merhaba Dunya'] };

const smsMessage = getMessage(sms); // string[]

const email = { from: 'kh@kh.com', to: 'kkkk@kkkk.com', message: 'Hello World' };

const emailMessage = getMessage(email); // string

Leave a Reply

Your email address will not be published.