HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

Make a single property optional in TypeScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
singlemakeoptionaltypescriptproperty

Problem

In TypeScript, 2.2...

Let's say I have a Person type:

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}


And I'd like to create a function that returns a Person, but doesn't require a nickname:

function makePerson(input: ???): Person {
  return {...input, nickname: input.nickname || input.name};
}


What should be the type of input? I'm looking for a dynamic way to specify a type that is identical to Person except that nickname is optional (nickname?: string | undefined). The closest thing I've figured out so far is this:

type MakePersonInput = Partial & {
  name: string;
  hometown: string;
}


but that's not quite what I'm looking for, since I have to specify all the types that are required instead of the ones that are optional.

Solution

You can also do something like this, partial only some of the keys.

type Omit = Pick>
type PartialBy = Omit & Partial>

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}

type MakePersonInput = PartialBy

Code Snippets

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}

type MakePersonInput = PartialBy<Person, 'nickname'>

Context

Stack Overflow Q#43159887, score: 329

Revisions (0)

No revisions yet.