Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print type object in typescript

Tags:

typescript

Is there an option in typescript to take a custom type, say:

type myCustomType = {
    type1: string
    type2: number
}

and use it in a variable? say

const theTypeIWantToPrint = getTypeAsString(myCustomType.type2)
console.log(theTypeIWantToPrint) // prints "number"

or just plainly do console.log(getTypeAsString(myCustomType.type2))

like image 635
m144 Avatar asked Oct 20 '25 03:10

m144


1 Answers

No, there's no way to do that in regular TypeScript code.

TypeScript types are only a development-time helper. When your TypeScript source code files (.ts, .tsx, etc.) get turned into JavaScript, those types are removed. From JavaScript's perspective, it's as if you never wrote them to begin with.

You can preview how types are erased on the TypeScript Playground. Here's a playground with this question's code. Given this input:

type MyCustomType = {
    type1: string
    type2: number
}

let value: MyCustomType;

You can see on the .JS tab on the right that the code getting run doesn't have type MyCustomType or : MyCustomType. The output is:

let value;

This article goes more in depth: https://www.totaltypescript.com/typescript-types-dont-exist-at-runtime

like image 77
Josh Avatar answered Oct 22 '25 05:10

Josh



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!