How are the TypeScript Partial and Required types implemented?
I find it important to know how the most-used TypeScript utility types are implemented. Here, we see the implementation of the Partial (all properties of a...
I find it important to know how the most-used TypeScript utility types are implemented.
Here, we see the implementation of the Partial (all properties of a type are optional) and Required (all properties of a type are required) types.
Knowing this is essential because it allows you to customize or create a new behavior for your use cases.
keyof Persongenerates a union of the keys of Person, sokeyof Personresults in"id" | "name".[key in keyof Person]iterates over each key in that union.Person[key]is the type of the property in Person associated with the key, so "id" is a number, and "name" is a string.- The
?modifier makes the property optional (used for thePartialtype), while the-?modifier removes the optional modifier from the property, making it required (used for theRequiredtype).
partial.tstypePerson={id:number,name:string}// 🪄 Use the ? modifier to make a property optionaltypePersonPartial={keyinkeyofPerson?:Personkey};const:PersonPartial={:}// ^? { id?: number | undefined; name?: string | undefined }// 🔁 Refactor into a generic typetypeGenericPartial<T>={keyinkeyofT?:Tkey};const:GenericPartial<Person>={:}// ^? { id?: number | undefined; name?: string | undefined }// Use the built-in Partial Type:// Constructs a type with all properties of Type// set to optional. This utility will return a type that represents// all subsets of a given type.const:Partial<Person>={:}// ^? { id?: number | undefined, name?: string | undefined }
required.tstypePerson={id?:number,name?:string}// 🪄 Use the -? modifuer to make a property required// (by removing the optional ? modifier)typePersonRequired={keyinkeyofPerson-?:Personkey};const:PersonRequired={:3,:}// ^? { id: number; name: string }// 🔁 Refactor into a generic typetypeGenericRequired<T>={keyinkeyofT-?:Tkey};const:GenericRequired<Person>={:3,:}// ^? { id: number; name: string }// Use the built-in Required Type:// Constructs a type consisting of// all properties of Type set to required.const:Required<Person>={:3,:}// ^? { id: number, name: string }
Feel free to update this developer bit on GitHub, thanks in advance!