unknown

In the Basic Types lesson, you met any, which turns the type checking off: TypeScript allows everything, and the bugs of JavaScript come back. Sometimes, though, you really don't know what a value is. Data that come from outside the program, such as a saved game, a file, or a message from a server, can contain anything: maybe the number you expect, maybe a text, maybe nothing at all.

For such values, TypeScript has the type unknown. Like any, it accepts every value. Unlike any, it doesn't let you do anything with the value until you find out what it is:

const savedName: unknown = "Kira";
console.log(savedName);
console.log(savedName.toUpperCase());
main.ts(3,13): error TS18046: 'savedName' is of type 'unknown'.

Printing is fine, because console.log accepts anything. But a method isn't: the value could be a number, and then the program would crash. You also can't store an unknown in a variable of another type: const heroName: string = savedName; gives error TS2322: Type 'unknown' is not assignable to type 'string'.

You get to the value by narrowing it, with the checks you know:

const savedName: unknown = "Kira";

if (typeof savedName === "string") {
    console.log(savedName.toUpperCase());
} else {
    console.log("The save file has no name");
}

This prints:

KIRA

Inside the if, savedName is a string, and everything that works for texts is allowed. That's the whole difference between the two types. With any, you can forget to check, and the program crashes when it runs (with const savedName: any = 42;, the call ends with TypeError: savedName.toUpperCase is not a function). With unknown, you can't forget: TypeScript requires the check.

So when you don't know the type of a value, write unknown, not any. And when you see any in a program, ask yourself whether a real type, or at least unknown, would do.

Instructions

The program prints 130, 4510, 10 and 11. The second number is wrong: the saved gold was the text "45", and "45" + 10 gives the text "4510". any hid the problem. Change the type of saved to unknown, and TypeScript reports the return. Fix the function: when saved is a number, return it; otherwise, return 0 for now. The program then prints 130 and three times 10.

Add one more check: when saved is a text, return Number(saved). The program then prints:

130
55
10
10

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/10