Primitive Types & Special Types
At the core of TypeScript is its type system. Understanding basic primitive types and special control types is essential for writing robust, type-safe code. Let us examine the fundamental types.
1. JavaScript Primitives
TypeScript supports all JavaScript primitive types. You declare them using type annotations after a variable name.
const isCompleted: boolean = true;
const totalScore: number = 98.5;
const headingText: string = "TypeScript Tutorial";
const emptyValue: null = null;
const notDefined: undefined = undefined;- number: Represents both integers and floating-point values.
- string: Represents textual data. Supports template strings.
- boolean: Represents logical true or false.
2. The Escape Hatch: any
The any type represents any JavaScript value. When a variable is typed as any, the compiler shuts down type checking for that variable.
let dynamicValue: any = 42;
dynamicValue = "Hello World"; // No compiler error
dynamicValue.callNonExistentMethod(); // No compiler error, but will crash at runtime![!WARNING]
Avoid using any wherever possible. It turns off type-checking, defeating the primary purpose of using TypeScript.3. The Safe Alternative: unknown
The unknown type is the type-safe counterpart to any. Like any, you can assign any value to an unknown variable. However, you cannot perform operations on an unknown value until you narrow down its type.
let secureValue: unknown = "Sample Text";
// This will fail compiler check:
// secureValue.toUpperCase();
// We must narrow the type first:
if (typeof secureValue === "string") {
console.log(secureValue.toUpperCase()); // Works perfectly!
}Use unknown when you do not know the type of incoming data (e.g., from an API request) but want to enforce safety checks before processing it.
4. void vs never
These two types represent the absence of values, but they are used in different contexts.
void
Use void to represent the return type of functions that do not return a value (e.g., they only trigger side effects).
function printMessage(message: string): void {
console.log(message);
}never
The never type represents values that will never occur. In functions, it is used as the return type when a function never returns control to its caller (e.g., it throws an error or loops infinitely).
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}5. Summary
- Use standard primitive types (
string,number,boolean) for basic data. - Avoid
anyto keep type checking active. - Use
unknownfor dynamic values where you want to force type checks before execution. - Return
voidfrom functions that perform actions without returning data. - Return
neverfor code paths that terminate execution or run indefinitely.