Narrow what a value can be

INPUT · Slides

Avoid any, use unknown

01 / 05

any is a declaration of "no need to look"

When you do not know the type, writing any makes the error go away. But what went away is only the error — the problem is still sitting there.

Wherever you write any, TypeScript stops looking at all. Call a method that does not exist and it lets you through. The code below passes the type check and falls over when you run it.

const value: any = "Yui";console.log(value.toFixed(2));

Result

TypeError: value.toFixed is not a function

02 / 05

any spreads to what is around it

Put an any value into another variable and that one stops being looked at as well. One any written in one place switches off the checking downstream too.

The code below puts text into a number variable and nothing is said. Run it and you get NaN.

const value: any = "Yui";const count: number = value;console.log(count * 2);

Result

NaN

03 / 05

unknown is "not known yet"

What you use instead is unknown. It means "I do not know what this is right now", and anything can go into it.

The difference is on the way out. While it is still unknown, it will not let you put it into a variable of another type.

const value: unknown = "Yui";const text: string = value;

Result

Type error: Type 'unknown' is not assignable to type 'string'.

04 / 05

Check it and you can use it

unknown becomes usable inside a check with typeof, exactly the narrowing you did in the last lesson.

The difference between the two fits in one line. any lets you through without checking; unknown will not let you through until you check.

const value: unknown = "Yui";if (typeof value === "string") {  console.log(value.length);}

Result

3

05 / 05

When in doubt, unknown

When you take in something whose contents you do not know, make it unknown. It forces the shape where you always check before use, so there is no way to forget.

Time to write some. You will not need any.

function show(value: unknown): void {  if (typeof value === "number") {    console.log(value * 3);  } else {    console.log("not a number");  }}show(7);show("seven");

Result

21
not a number