-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Change property modifier in mapped type based on condition #32562
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
export type ModelFromSchema<T> = {
[P in keyof T]+?:
T[P] extends MakeItRequired<infer U> ? unknown :
ModelValue<T[P]>
} & {
[P in keyof T]-?:
T[P] extends MakeItRequired<infer U> ? ModelValue<U> :
unknown
}
EDIT 1: No, I was too happy about it. It doesn't work. EDIT 2: Okay, found a resolution: type MakeItRequiredKeyNames<T> = { [K in keyof T]: T[K] extends MakeItRequired<infer U> ? K : never }[keyof T];
type MakeItRequiredKeys<T> = Pick<T, MakeItRequiredKeyNames<T>>;
type NonMakeItRequiredKeyNames<T> = { [K in keyof T]: T[K] extends MakeItRequired<infer U> ? never : K }[keyof T];
type NonMakeItRequiredKeys<T> = Pick<T, NonMakeItRequiredKeyNames<T>>;
export type ModelFromSchema<T> = {
[P in keyof NonMakeItRequiredKeys<T>]?:
T[P] extends MakeItRequired<infer U> ? never :
ModelValue<T[P]>
} & {
[P in keyof MakeItRequiredKeys<T>]:
T[P] extends MakeItRequired<infer U> ? ModelValue<U> :
never
} |
Just note that your types might look a little "ugly" in the tooltip. It'll still work just fine, though. If you want to make it look a little better (maybe for debugging or something), Identity<T> = T;
Merge<T> = (
T extends any ?
Identity<{ [k in keyof T] : T[k] }> :
never
); Then, type Blah = Merge<ModelFromSchema<T>>; When you hover over I'm on mobile and can't test it but I think the above works. I'll check again when I get home |
Possibly relevant comment from another somewhat related issue (#31581, about detecting such modifiers) I'd be interested in more streamlined manipulation of modifiers in mapped types. Detecting `readonly` and optional properties is indeed a bunch of hoop jumping, and then if you want to selectively *alter* the modifiers, you need to split the mapping into pieces and intersect them: |
This works, but also seems to turn types like |
As I know there is no way to change property modifier of mapped types based on conditional types. Here is my use case:
My goal is to have
id
non optional, while having others optional.Additional screenshoot from vscode:
Can we have this feature?
The text was updated successfully, but these errors were encountered: