Understanding TypeScript's Type System
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
TypeScript is a superset of JavaScript that introduces static typing to help developers catch errors early and improve code maintainability. This blog will explore the key TypeScript types and features that enhance development efficiency.
The Primitives: string, number, and boolean
In TypeScript, primitive types are fundamental data types:
let username: string = "John";
let age: number = 30;
let isActive: boolean = true;
Arrays
Arrays store multiple values of a specific type:
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob"];
any
The any type allows dynamic typing but should be avoided when possible:
let value: any = "Hello";
value = 42; // No error
noImplicitAny
Enabling noImplicitAny in tsconfig.json forces explicit type annotations to prevent accidental any usage.
Type Annotations on Variables
Explicitly declaring types improves readability and catches errors early:
let message: string = "Welcome to TypeScript!";
Functions
Parameter Type Annotations
Specify the type of parameters:
function greet(name: string): string {
return Hello, ${name}!;
}
Return Type Annotations
Define the return type of functions:
function add(a: number, b: number): number {
return a + b;
}
Anonymous Functions
TypeScript can infer types in anonymous functions:
const multiply = (x: number, y: number): number => x * y;
Object Types
Objects with defined properties improve type safety:
let user: { name: string; age: number } = { name: "John", age: 25 };
Optional Properties
Use ? for optional properties:
interface User {
name: string;
age?: number;
}
Union Types
Defining a Union Type
A variable can hold multiple types:
let id: string | number;
id = "123";
id = 123;
Working with Union Types
Using type guards ensures correct operations:
领英推荐
function displayId(id: string | number): void {
if (typeof id === "string") {
console.log("ID as string: ", id.toUpperCase());
} else {
console.log("ID as number: ", id.toFixed(2));
}
}
Type Aliases
Define custom types for better readability:
type ID = string | number;
let userId: ID;
Interfaces
Interfaces define object structures:
interface Person {
name: string;
age: number;
}
Differences Between Type Aliases and Interfaces
Type Assertions
Convert types when TypeScript is unsure:
let input: any = "Hello";
let strLength: number = (input as string).length;
Literal Types
Define specific allowed values:
let role: "admin" | "user";
role = "admin";
Literal Inference
Using const ensures the value does not change:
const direction = "left";
null and undefined
strictNullChecks Off
If strictNullChecks is off, null and undefined can be assigned to any variable.
strictNullChecks On
If enabled, null and undefined must be explicitly handled.
Non-null Assertion Operator (Postfix !)
Force TypeScript to ignore potential null values:
let name: string | null = getName();
console.log(name!.length);
Enums
Enums define named constants:
enum Status {
Success,
Failure,
Pending,
}
Less Common Primitives
bigint
For large integers:
let big: bigint = 9007199254740991n;
symbol
For unique values:
const sym1 = Symbol("key");