Issue
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.
Solution
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'>
Answered By - Damian PieczyĆski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.