Want a faster signal before interviews? Take the Interview Ready Check →

DAY 17 OF 30

any and unknown

Yesterday, in one sentence

What is a discriminated union in TypeScript?

Interview question

Why does the discriminant in a discriminated union have to be a literal type, and not a primitive type like string?

any turns off type checking completely and allows any type to be passed through without checking.

let power: any = "telepathy";

power.toUpperCase(); // ok
power.fly(); // ok, no such method, but no error either
power = 41; // ok

This could cause errors. The power.fly() line above would throw an error that only shows up when you run your code.

Sometimes you genuinely do not know what a type will be. For example, a response from an API call still needs a type, but you have no guarantee what is in it until you look. You can use the type unknown for this. The value can be anything, just like any, but you cannot use it until you narrowNarrowing it.

let power: unknown = "telepathy";

power.toUpperCase();
// ❌ 'power' is of type 'unknown'

if (typeof power === "string") {
  power.toUpperCase(); // ok, power is string here
}

Check yourself

Which line errors?
let a: any = "hero"
let b: unknown = "hero"

a.toUpperCase()
b.toUpperCase()
What is the difference between any and unknown?