typescript / beginner
Snippet
The unknown Type
The unknown type is a safer alternative to any. It forces you to perform a type check before you can access properties or methods on the value, preventing runtime errors.
snippet.ts
1
2
3
4
let input: unknown = "Hello";if (typeof input === "string") {let len: number = input.length;}
Breakdown
1
let input: unknown = "Hello";
Declares a variable with the unknown type, meaning its specific type is not yet confirmed.
2
if (typeof input === "string") {
Uses a type guard to check if the value is actually a string at runtime.
3
let len: number = input.length;
Safely accesses the length property now that the compiler knows the variable is a string.