4 min read
•Question 13 of 48mediumWhat are Partial and Required utility types?
Making properties optional or required.
What You'll Learn
- Partial<T> utility
- Required<T> utility
- Use cases
Partial<T>
Makes all properties optional.
code.tsTypeScript
interface User {
name: string;
email: string;
age: number;
}
// All properties become optional
type PartialUser = Partial<User>;
// { name?: string; email?: string; age?: number; }
// Great for update functions
function updateUser(id: string, updates: Partial<User>) {
// Can pass any subset of properties
}
updateUser("123", { name: "John" }); // OK
updateUser("123", { age: 31 }); // OKRequired<T>
Makes all properties required.
code.tsTypeScript
interface Config {
host?: string;
port?: number;
ssl?: boolean;
}
// All properties become required
type RequiredConfig = Required<Config>;
// { host: string; port: number; ssl: boolean; }
function initServer(config: Required<Config>) {
// All properties guaranteed
}Combining Utility Types
code.tsTypeScript
interface Post {
id: string;
title: string;
content: string;
author?: string;
}
// Create post without id
type CreatePost = Partial<Omit<Post, "id">>;