Make some properties optional in TypeScript

Partial makes everything optional, which is rarely what you want. Here is the targeted version.

SNP 106 #B25 Filed typescript

typescript
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>

Use it when a function creates something and fills in a few fields itself:

typescript
interface Post {
  id: string
  title: string
  publishedAt: Date
  draft: boolean
}

type NewPost = Optional<Post, 'id' | 'publishedAt'>

function createPost(input: NewPost): Post {
  return { id: crypto.randomUUID(), publishedAt: new Date(), ...input }
}

The reverse, making a few optional fields required, is Omit<T, K> & Required<Pick<T, K>>.