Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a single property optional in TypeScript

Tags:

typescript

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<Person> & {   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.

like image 602
DallonF Avatar asked Apr 01 '17 17:04

DallonF


People also ask

How do you make a field optional in TypeScript?

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!

How do you make all properties of an interface optional?

To make all of the properties of a type optional except one, use an interface to extend the type passing it to the Partial utility type, e.g. interface OptionalExceptSalary extends Partial<Employee> {} and override the specific property setting it to required.

How do you omit a property in TypeScript?

Use the Omit utility type to exclude a property from a type, e.g. type WithoutCountry = Omit<Person, 'country'> . The Omit utility type constructs a new type by removing the specified keys from the existing type. Copied!

Does TypeScript have optional?

TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.


1 Answers

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

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'> 
like image 120
Damian Pieczyński Avatar answered Dec 04 '22 02:12

Damian Pieczyński