JSTAcademy
0 XP
Dashboard
Crash Courses
Utility Types
10 min
Masters+175 XP
Crash Courses · Masters

Utility Types

Use TypeScript built-in utility types to transform and compose existing types.
10 min read+175 XP on completionCert: TypeScript Crash Course
Tap any word in the text below to start reading from there.

Utility Types

TypeScript ships with utility types that transform existing types — no need to rewrite manually.

Partial and Required

interface User { id: string; name: string; email: string; bio: string }

type UserUpdate = Partial<User>
// { id?: string; name?: string; email?: string; bio?: string }

async function updateUser(id: string, data: Partial<User>): Promise<User> {
  return fetch('/api/users/' + id, {
    method: 'PATCH',
    body: JSON.stringify(data),
  }).then(r => r.json())
}

Pick and Omit

interface User {
  id: string; name: string; email: string
  passwordHash: string; bio: string
}

// Only these fields
type PublicUser = Pick<User, 'id' | 'name' | 'bio'>

// Everything except passwordHash
type SafeUser = Omit<User, 'passwordHash'>

Record

type TrackColors = Record<'tech' | 'marketing' | 'trading', string>

const colors: TrackColors = {
  tech: '#378add', marketing: '#c9a84c', trading: '#2d8a4e',
}

// Dynamic lookup map
type CourseLookup = Record<string, Course>
const byId: CourseLookup = {}
courses.forEach(c => { byId[c.id] = c })

ReturnType and Parameters

function createUser(name: string, email: string) {
  return { id: crypto.randomUUID(), name, email, createdAt: new Date() }
}

type NewUser = ReturnType<typeof createUser>
// { id: string; name: string; email: string; createdAt: Date }

Combining Utility Types

type CourseForm = Partial<Omit<Course, 'id' | 'createdAt'>>
type ImmutableConfig = Readonly<Record<string, string>>
0%