Let's explore some of the advanced types that TypeScript offers and how they can be applied effectively:
- Aliases
type Student = {
readonly id: number;
name: string;
retire: (date: Date) => void;
};
let student: Student = {
id: 1,
name: 'bayu',
retire: (date: Date) => {
console.log(date);
},
};
- Intersection
type Draggable = {
drag: () => void;
};
type Resizeable = {
resize: () => void;
};
type UIWidget = Draggable & Resizeable;
let textBox: UIWidget = {
drag: () => {},
resize: () => {},
};
- Literal
type Quantity = 50 | 100;
type Metric = 'cm' | 'mm';
let quantity: Quantity = 50;
let metric: Metric = 'cm';
- Never
function processEvent(): never {
while (true) {
// read a message from a queqe
}
}
processEvent();
console.log('Hello World');
// clg never executed
- Nullable
function great(name: string | null | undefined) {
if (name) console.log(name.toUpperCase());
else console.log('parameter is nullable');
}
great(undefined);
- Nullish Coaelscing
let speed: number | null = null;
let ride = {
// speed: speed !== null ? speed : 30
speed: speed ?? 30,
};
- Optional Changing
type Customer = {
birthday?: Date;
};
function getCostumer(id: number): Customer | null | undefined {
return id === 0 ? null : { birthday: new Date() };
}
let customer = getCostumer(1);
// optional property access operator
console.log(customer?.birthday?.getFullYear());
// optional element access operator ex: array customer
// customer?.[0]
// optional call
let log: any = null;
log?.('a');
- Union
function convertion(weight: number | string) {
if (typeof weight === 'number') return weight * 2;
else return parseInt(weight) * 2;
}
convertion(10);
convertion('10');
- Unknown
function render2(document: unknown) {
// Narrowing
if (typeof document === 'string') {
document.toUpperCase();
}
// document.fly()
// document.whatEverYouWant()
}
Advanced types in TypeScript equip you with powerful tools to handle complex scenarios, create reusable patterns, and ensure type safety in your projects. By employing union types, intersection types, conditional types, mapped types, type guards, template literal types, and even recursive types, you can elevate your code to new levels of expressiveness and maintainability.
This blog post has introduced you to the significance of advanced types, how they solve common development challenges, and how to apply them in various scenarios. Armed with this knowledge, you're ready to tackle intricate type relationships and create more resilient and adaptable TypeScript applications.
Hope this helps!
Top comments (0)