Skip to content

Instantly share code, notes, and snippets.

@chris-mcdonald-dev
Last active December 29, 2023 11:20
Show Gist options
  • Save chris-mcdonald-dev/8c19035612296e0bff474dfd476f40cd to your computer and use it in GitHub Desktop.
Save chris-mcdonald-dev/8c19035612296e0bff474dfd476f40cd to your computer and use it in GitHub Desktop.
TypeScript: Make Specific Properties Optional/Required - (A Custom Utility)

A custom utility to make specific keys optional

type OptionalKeys<TType, TKey extends keyof TType> = Omit<TType, TKey> & Partial<Pick<TType, TKey>>

A similar utility to make specific keys required

type RequiredKeys<TType, TKey extends keyof TType> = Omit<TType, TKey> & Required<Pick<TType, TKey>>

Examples of how they're used

// An example of a type we want to modify
type Person {
  name: string;
  hometown: string;
  nickname: string;
}

// Example creating a variable of type Person with an optional "nickname" property.
const myPerson1: OptionalKeys<Person, 'nickname'> = {
  name: 'Deandre',
  hometown: 'Seoul'
}

// Example doing the same thing with multiple optional properties.
const myPerson2: OptionalKeys<Person, 'nickname' | 'hometown'> = {
  name: 'Ashley'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment