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.
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!
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.
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!
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.
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'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With