any: Turning the Check Off
TypeScript has a type that makes every error go away: any. A variable of the type any can hold anything, and TypeScript allows anything with it: every property, every method, every operation. It simply stops checking:
let loot: any = "golden crown";
console.log(loot.toUpperCase());
console.log(loot.toUppercase());TypeScript reports nothing, and the program runs. It prints GOLDEN CROWN and then crashes on the typo:
TypeError: loot.toUppercase is not a functionThat's exactly the JavaScript behavior TypeScript is supposed to protect you from. With let loot: string = "golden crown";, or just let loot = "golden crown";, TypeScript would find the typo before the program runs: Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?
And any spreads. Whatever you read from an any value is any too, so TypeScript doesn't check it either:
let loot: any = { name: "Golden Crown" };
const title = loot.nmae;
console.log(title.toUpperCase());No error from TypeScript again, but when the program runs, title is undefined, and it crashes with TypeError: Cannot read properties of undefined (reading 'toUpperCase').
Why does any exist, then? It helps when a large JavaScript program is moving to TypeScript bit by bit, and you'll also meet it in older code. It's also tempting to write it when an error message is in your way: the message disappears, but the mistake stays and shows up when the program runs. So avoid any. When you really don't know what a value will be, lesson 5 has a safe alternative: unknown.
When TypeScript would have to use any without you writing it, it tells you: messages with the words implicitly has … 'any', such as the one for the empty array in the exercise on arrays, mean that it can't work out the type, and that you should write it.
Instructions
Run the program: it crashes with a TypeError. Replace any in treasure with its real type, string. TypeScript now finds the mistake before the program runs: fix it. The program then prints Kira finds the GOLDEN CROWN, but Kira's gold is a strange 120300.
Replace any in value with number. TypeScript now reports the next mistake. Fix it, so that the program prints:
Kira finds the GOLDEN CROWN
Gold: 420Start programming for free
8/9