Middle
Are you familiar with TypeScript? What are utility types, and can you give examples?
sobes.tech AI
Answer from AI
Utility types in TypeScript are built-in types that allow transforming or combining other types for convenience and code reduction.
Examples:
Partial<T>— makes all properties of typeToptional.Required<T>— makes all properties of typeTmandatory.Readonly<T>— makes all properties of typeTread-only.Pick<T, K>— selects only the properties with keysKfrom typeT.Omit<T, K>— excludes properties with keysKfrom typeT.
Example:
type User = {
id: number;
name: string;
age?: number;
};
// All properties are optional
const updateUser: Partial<User> = { name: "Alice" };
// Only id and name
type UserPreview = Pick<User, "id" | "name">;
// All properties are read-only
const readonlyUser: Readonly<User> = { id: 1, name: "Bob" };