I havve the following types:
type A = {
role: 'admin',
force?: boolean
}
type B = {
role: 'regular'
}
type Req = { data: number } & (A | B);
When when I do some manipulation on Req
force
is removed for some reason:
type NoData = Omit<Req, 'data'>;
const noData: NoData = {
role: 'admin',
force: true
}
and I get:
Type '{ role: "admin"; force: boolean; }' is not assignable to type 'NoData'.
Object literal may only specify known properties, and 'force' does not exist in type 'NoData'.(2322)
CodePudding user response:
The default version ofOmit
is not distributive, meaning it will apply to the union as a whole, or more specific to the common properties of the union, rather than to each constituent of the union
You can create a distributive version using distributive conditional types :
type A = {
role: 'admin',
force?: boolean
}
type B = {
role: 'regular'
}
type Or = { data: number } & (A | B);
type DistributiveOmit<T, K extends PropertyKey> = T extends T ? Omit<T, K> : never;
type NoData = DistributiveOmit<Or, 'data'>;
const noData: NoData = {
role: 'admin',
force: true
}