Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript find type of union type

I want to know the type c in printTypeOf function. Here is my code:

type Email ={
    email:string,
}
type Phone ={
    phone:string,
}
type ContactInfo = Email | Phone;

function printTypeOf(c: ContactInfo) {
    console.log(typeof c)
}

const x: Email = { email: "X" };
printTypeOf(x);

Current output is object but I need to find if it is Email or Phone

like image 570
mohsen saremi Avatar asked Oct 19 '25 01:10

mohsen saremi


1 Answers

You can't print a name of a type because once TypeScript is transpiled to JavaScript all the type information is lost. It prints object because that's what the TypeScript turns into once you have running code.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!