DAY 17 OF 30
any and unknown
Yesterday, in one sentence
A union where every member has a property with the same name, each given a different literal type. Checking that property narrows the whole object to one member.
Did you say:
- ✓a union of object types
- ✓each has the same property with a different literal type
- ✓checking that property narrows to one of them
Interview question
string?Because a literal type allows only one exact value. If it were string, every
object type in the union would accept any string, so checking it would not tell
TypeScript which one you have.
Did you say:
- ✓a literal type allows one exact value
- ✓`string` would match every object type in the union
- ✓nothing to narrow with
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
let a: any = "hero"
let b: unknown = "hero"
a.toUpperCase()
b.toUpperCase()
any switches off checking, so anything is allowed. unknown needs narrowing before you can use the value.
any and unknown?Both accept any value. any switches off type checking, so you can do anything
with it. unknown keeps checking on, so you have to narrow it before you can
use it.
Did you say:
- ✓both accept any value
- ✓`any` switches off type checking
- ✓`unknown` must be narrowed before use