Middle
How do you create and use custom types in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, you can create custom types using the keywords type and interface.
typeallows you to create aliases for types, combine types through unions (|) or intersections (&).interfaceis used to describe the structure of objects, classes, and can be extended.
Example of creating a custom type and interface:
// Type alias
type ID = string | number;
// Interface for a user object
interface User {
id: ID;
name: string;
age?: number; // optional property
}
// Usage
const user: User = { id: 123, name: "Ivan" };
function printUser(user: User) {
console.log(`${user.name} (${user.id})`);
}
printUser(user);
Thus, custom types help describe data structures and provide static typing in the code.