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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With