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

Dav*_*ter 7 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? */
Run Code Online (Sandbox Code Playgroud)

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?

Bra*_*rad 5

我不知道等效于reveal_type,但您可以强制无效分配并检查产生的错误消息。分配到never总是失败1,所以在你的例子中:

var timer = window.setTimeout(...);
const revealType : never = timer;
Run Code Online (Sandbox Code Playgroud)

应该导致编译器打印:

Type 'number' is not assignable to type 'never'
Run Code Online (Sandbox Code Playgroud)

1除非您正在检查的类型也是never