Kodokon kodokon.com

Inference, any and unknown

Let TypeScript figure out types with inference, and understand why unknown beats the dangerous any.

8 min · 3 questions

Open this lesson in Kodokon

Good news: you don't have to annotate every variable. Thanks to type inference, TypeScript figures out a variable's type from the value you give it. Writing let city = "Lyon" is enough: TypeScript knows that city is a string and protects it as if you had annotated it.

TYPESCRIPT
let city = "Lyon"; // inferred type: string
let count = 3;     // inferred type: number

count = count + 1; // accepted
// city = 42; -> error: city is still a string
No annotations, yet the types are all there.

The any type means "anything". An any variable escapes all checks: TypeScript accepts everything, without verifying. It is like removing your seatbelt: the code compiles, but errors come back at runtime - exactly what TypeScript was supposed to prevent.

TYPESCRIPT
let data: any = "hello";
data = 42; // accepted without complaint

// Compiles, but crashes at runtime:
// data.toUpperCase() does not exist on a number!
With any, TypeScript looks the other way.

For a value whose type is genuinely unknown (a server response, user input), prefer unknown. Like any, it accepts any value, but it forces you to check the type (for example with typeof) before using it. Safety therefore remains intact.

TYPESCRIPT
let value: unknown = "hello";

// console.log(value.toUpperCase()); -> rejected!

if (typeof value === "string") {
  console.log(value.toUpperCase()); // "HELLO"
}
unknown requires a check before use.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is type inference?
    • TypeScript figures out the type from the initial value
    • TypeScript removes types from the program
    • TypeScript converts numbers into texts
  2. Why should any be avoided as much as possible?
    • It slows down the program
    • It disables TypeScript's checks
    • It is forbidden by the language
    • It only works with numbers
  3. What must you do before using a value of type unknown?
    • Check its type, for example with typeof
    • Convert it to any
    • Declare it a second time