In this video, you followed one saved price at Spoke & Sprocket from JSON.parse() all the way to a quote total, first as any and then as unknown.
Key Points
anyswitches the checker off for a value. Whatever you do with it goes through unchecked.anydoesn’t always stay where it starts. In this example, a function that returns it with no return type, a variable that holds it, and a total added up from it all becomeanytoo, so the missing checks spread all the way to the result.anygets in three common ways. A function can hand it back, asJSON.parse()does. You can write it yourself, as: any. A parameter with no type is an implicitany, which strict mode reports. The first two get in silently, so they’re the ones to look for. Follow ananyback to where it first enters, and fix it there.unknownaccepts every value too, but it blocks anything that needs a particular type, like adding to it, until you’ve checked what it is. You can still store it, log it or check it with===. Because a return type is a promise about what comes out,: unknownonsavedPrice()stops theanyinside the function. The checker reports'tube' is of type 'unknown'.where the code adds totubewithout a check. You can also write: unknownon the variable that holds the parsed value, as inconst tube: unknown = JSON.parse(text);.- One
typeofcheck makes anunknownvalue usable. Insideif (typeof tube === "number") { ... }, the checker reads the check and givestubethe narrower typenumber. That’s called narrowing, and that’s all you need about it for now. The same check works with"string", for a value that should be text. - The check works at run time because
typeofis plain JavaScript. Theunknownannotation is erased before Node runs the file, but thetypeofcheck stays and runs. - The rule: for a value whose type you don’t know yet, choose
unknownoverany, and check its type before you use it as one.
The Code
The first version reads the inner tube’s saved price with JSON.parse(). The saved text is "799", with quotes, so the value is a string: