I have some code like the following where I want to determine what type TypeScript has inferred for an expression:
var timer = window.setTimeout(...);
/* QUESTION: What is the inferred type of "timer" here? */
When I use the mypy typechecker for Python, I can insert the special expression reveal_type(my_expression)
into code to have the typechecker print a fake error containing the inferred type for expression my_expression
.
Is there a way I can ask the TypeScript tsc
type-checker for similar information about the inferred type of an expression?
TypeScript infers types of variables when there is no explicit information available in the form of type annotations. Types are inferred by TypeScript compiler when: Variables are initialized. Default values are set for parameters.
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
Bookmark this question.
TypeScript automatically finds type definitions under node_modules/@types , so there's no other step needed to get these types available in your program.
I don't know of an equivalent to reveal_type
, but you can force an invalid assignment and inspect the resulting error message. Assignment to never always fails1, so in your example:
var timer = window.setTimeout(...);
const revealType : never = timer;
Should cause the compiler to print:
Type 'number' is not assignable to type 'never'
1 Unless the type you're checking is also never
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