6

Often TS fails for me because the type it infers is different from what I expect it to be. I could force typecast variables, but I'd prefer to figure out why TS isn't inferring the types correctly.

Is there a way to print the type that TS believes a variable is?

E.g.:

const obj = [
  { a: 'foo' },
  { b: 'bar' },
];

printTsType(obj[0].a);

I would expect this to be the literal 'foo', but I think TS just infers string.

11
  • typeof(obj[0].a) isn't this? Commented Jun 17, 2020 at 15:56
  • 2
    "Is there a way to print the type that TS believes a variable is?" no. The type system exists at compile time, not when the code is running. Commented Jun 17, 2020 at 15:58
  • 2
    @VLAZ when TS is compiling, I want the compiler to dump whatever type it inferred when it hits a particular line. I guess it should be a compiler directive and not a JS function Commented Jun 17, 2020 at 16:01
  • 1
    Your editor should be able to tell you what something is if you hover your mouse over it, for example. If you want it programmatically, then you'd need to get a hold of the intermediate representation that TS produces. This should be exposed somehow as people have wrote plugins using that information. Commented Jun 17, 2020 at 16:03
  • 1
    @LeoJiang You could force TS to infer type of obj[0].a to be 'foo' by using {a: 'foo' as const} or const obj = [...] as const depending on your requirements. Commented Jun 17, 2020 at 16:06

1 Answer 1

13

One trick to learn what is the inferred type is to pass that variable to a function that expects a different type (e.g. never) to generate a compiler error which will tell you "inferred type is not assignable to never". TS Playground example: here

Sign up to request clarification or add additional context in comments.

2 Comments

Even shorter way is let foo: never = objectWithUnknownType
For now I prefer this to installing some ide or intellisense to use typescript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.