Problem
I'm trying to define a generic RequiredProps<T, K>
so that I can require a key K
on an interface T
to be non-nullable.
For example:
interface User {
id: string;
phoneNumber?: string;
}
type UserWithPhoneNumber = RequiredProps<User, 'phoneNumber'>
Should yield a type UserWithPhoneNumber
equivalent to { id: string; phoneNumber: string }
Solutions
With some trial and error I got something working:
type RequiredProps<T, K extends keyof T> = {
[P in Exclude<keyof T, K>]: T[P];
} & {
[P in K]-?: T[P];
};
This results in an equivalent type { name: string } & { phoneNumber: string }
, however for readability I would like it to be exactly { id: string; phoneNumber: string }
.
Looking at the other types in lib.es5.d.ts
I thought I could fix it using conditional types, however the following does not work:
type RequiredProps<T, K extends keyof T> = {
[P in keyof T]: P extends K ? NonNullable<T[P]> : T[P];
};
Why doesn't this work, and how can it be fixed?
Here's a CodeSandbox to tinker with: https://codesandbox.io/s/serene-meadow-j20w1?file=/src/index.ts