Annotations and Assertions 12 exercises

Global Typings use any

In this exercise, we are working with a function named getObj. This function parses a JSON string and assigns the parsed object to const obj:

const getObj = () => {
const obj = JSON.parse('{ "a": 123, "b": 456 }');
return obj;

Currently the inferred type for obj is

Loading exercise


00:00 In this exercise, we have a getObj function. Inside it, we're doing a const obj equals json.pass, and then we're passing some json. This json has a number and b number on it. But if we look at the definition for what's inferred for obj, it's typed as any.

00:17 Now, this is tricky because what we're expecting here is to get some errors if we try to access c on this thing. But TypeScript can't really break down this json for us dynamically and figure out exactly what's returned from it. So we need to add an annotation to obj

00:34 and try to basically make this test case pass down here. We just want this tsExpectError to go away and to force us to kind of make sure that when we're accessing it, we're only accessing a and b. And I want you, while you're solving this, to try to think, is any actually a good type

00:53 for json.pass to return? And is there any way that we can get around this and make it so that we have to actually kind of like pass this for ourselves? And what might an alternative better type for this be? Good luck.