I would like to propose two utility types:
RequiredExcept<T, Keys>
OptionalExcept<T, Keys>
These are essentially extensions of TypeScript's Required<T> and Partial<T> utilities.
There was an earlier discussion in #811, where the suggested solution was:
SetOptional<User, Exclude<keyof User, 'username'>>
This works, but I think the intent becomes much clearer with dedicated utilities:
OptionalExcept<User, 'username'>
RequiredExcept<User, 'bio'>
Motivation
I ran into this while working with Swagger/OpenAPI-generated types from a 3rd-party API that reuses the same schema for both create and retrieval operations.
Example:
type User = {
id?: string;
name?: string;
email?: string;
}
id is optional because it is omitted during creation, but retrieval responses effectively always include it.
We ended up repeatedly writing wrappers around SetRequired / SetOptional to express “everything required except X” or “everything optional except X”.
Notes
- The main value is clear intent and ergonomics.
- I also experimented with a more opinionated version of
RequiredExcept that removes undefined from required fields while preserving null, mainly because many APIs use null semantically while undefined often just reflects optionality:
type NonUndefined<T> = T extends undefined ? T & {} : T;
type RequiredExcept<
TRec extends Record<string, unknown>,
TOptional extends keyof TRec = never,
> = Simplify<
{
[K in TOptional]?: TRec[K];
} & {
[R in Exclude<keyof TRec, TOptional>]-?: NonUndefined<TRec[R]>;
}
>;
Though I suspect this behavior may be too opinionated for inclusion, especially considering interactions with exactOptionalPropertyTypes.
I would like to propose two utility types:
RequiredExcept<T, Keys>OptionalExcept<T, Keys>These are essentially extensions of TypeScript's
Required<T>andPartial<T>utilities.There was an earlier discussion in #811, where the suggested solution was:
This works, but I think the intent becomes much clearer with dedicated utilities:
Motivation
I ran into this while working with Swagger/OpenAPI-generated types from a 3rd-party API that reuses the same schema for both create and retrieval operations.
Example:
idis optional because it is omitted during creation, but retrieval responses effectively always include it.We ended up repeatedly writing wrappers around
SetRequired/SetOptionalto express “everything required except X” or “everything optional except X”.Notes
RequiredExceptthat removesundefinedfrom required fields while preservingnull, mainly because many APIs usenullsemantically whileundefinedoften just reflects optionality:Though I suspect this behavior may be too opinionated for inclusion, especially considering interactions with
exactOptionalPropertyTypes.