TypeScriptUtility types
Partial<Type>
Creates a type where every property is optional.
Example
#TypeScript
interface User {
id: number
name: string
email: string
}
function updateUser(user: User, changes: Partial<User>): User {
return { ...user, ...changes }
}
const emma: User = { id: 1, name: 'Emma', email: 'emma@example.com' }
const updated = updateUser(emma, { email: 'emma@codeworlds.com' })
console.log(updated)Result
{ id: 1, name: 'Emma', email: 'emma@codeworlds.com' }Definition and usage
#Partial<Type> takes an existing object type and returns a copy of it where every property has a question mark, meaning it’s optional. You don’t need to duplicate a definition just to allow incomplete data.
It’s most useful for updates: an updateUser function accepts only the fields that are changing, and the rest stay as they are. The same goes for forms filled out step by step, or for default settings overridden by the user.
Partial works shallowly. Nested objects stay exactly as they were, so their fields are still required.
Syntax
#Syntax
type New = Partial<Type>Type parameters
#Type
object type
The type whose properties should become optional.
More examples
#TypeScript
type UserDraft = Partial<User>
// type UserDraft = {
// id?: number
// name?: string
// email?: string
// }
const draft: UserDraft = { name: 'Jack' } // correct
const empty: UserDraft = {} // also correctTypeScript
interface Settings {
theme: 'dark' | 'light'
fontSize: number
sounds: boolean
}
const defaults: Settings = { theme: 'dark', fontSize: 16, sounds: true }
function createSettings(overrides: Partial<Settings>): Settings {
return { ...defaults, ...overrides }
}
console.log(createSettings({ sounds: false }))Result
{ theme: 'dark', fontSize: 16, sounds: false }Good practices
#- When you need the opposite, meaning to require every field, use
Required<Type>. - If only some fields should be optional, combine the types:
Omit<User, "email"> & Partial<Pick<User, "email">>.
Related entries
#Spotted a mistake or missing an example? Write to us.