I have a util function whose first parameter param
must include (simplified for example) the properties param.X
and param.Y
, but it doesn't matter what other properties it has. For instance it can also have param.Z
but that's not used by the util function and can be ignored.
How can I type the param such that it enforces this constraint without complaining something like Z not found on type ParamType
?
CodePudding user response:
Intersect the object type with Record<keyof any, unknown>
.
const fn = (obj: { x: string; y: string } & Record<keyof any, unknown>) => {
};
fn({x: 'x'}) // Fails
fn({x: 'x', y: 'y'}) // Passes
fn({x: 'x', y: 'y', z: 'z'}) // Passes
CodePudding user response:
Use Partial<ParamType>
. This allows you to specify only a subset of the type.
https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype