Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get TypeScript to reveal what type it has determined for an expression?

Tags:

typescript

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?

like image 818
David Foster Avatar asked Jul 07 '19 00:07

David Foster


People also ask

Does TypeScript have type inference?

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.

How do you check the data type of a variable in TypeScript?

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.

Does TypeScript enforce types?

Bookmark this question.

Where are TypeScript types defined?

TypeScript automatically finds type definitions under node_modules/@types , so there's no other step needed to get these types available in your program.


1 Answers

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

like image 92
Brad Avatar answered Sep 20 '22 20:09

Brad