typescript / beginner
Snippet
The 'unknown' Type
The 'unknown' type is a safer version of 'any'. You cannot perform operations on an 'unknown' value until you verify its type using a type check.
snippet.ts
1
2
3
4
5
let input: unknown = "Hello";if (typeof input === "string") {console.log(input.toUpperCase());}
Breakdown
1
let input: unknown = "Hello";
Declares a variable that could be anything, but its type is currently 'unknown'.
2
if (typeof input === "string") {
A type guard that narrows the type from 'unknown' to 'string' inside the block.