TypeScript Master (50 Qs)•Part 1: Basic & Foundational TypeScript (Junior / Entry-Level)
Compare `any`, `unknown`, and `never`.
junior LevelCode ExampleTypeScript
In Simple Words:
| Type | Meaning | Type Safety | Operations Allowed |
|---|---|---|---|
any | Completely disables type checking | None (escapes compiler) | Anything (calling methods, accessing properties) |
unknown | Type is unknown at compile time (Top Type) | High (type-safe) | No operations allowed until narrowed with type guards |
never | Value that can never occur (Bottom Type) | Maximum | No value can be assigned to never (except never) |
typescript
// 'any' is unsafe
let valAny: any = "hello";
valAny.nonExistentMethod(); // Compiles fine, crashes at runtime!
// 'unknown' is safe
let valUnknown: unknown = "hello";
// valUnknown.toUpperCase(); // Error: Object is of type 'unknown'
if (typeof valUnknown === "string") {
console.log(valUnknown.toUpperCase()); // Safe! Type narrowed to string
}
// 'never' represents unreachable code
function throwError(msg: string): never {
throw new Error(msg);
}