Home > other >  How to create a type that requires some properties but tolerates any additional properties?
How to create a type that requires some properties but tolerates any additional properties?

Time:03-14

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 ParamType does not include property Z?

CodePudding user response:

Intersect the object type with Record<PropertyKey, unknown>.

const fn = (obj: { x: string; y: string } & Record<PropertyKey, unknown>) => {
};

fn({x: 'x'}) // Fails
fn({x: 'x', y: 'y'}) // Passes
fn({x: 'x', y: 'y', z: 'z'}) // Passes

CodePudding user response:

There is already an answer(more granular), this one is only to show just another way(syntactically)...

type SomeRequired = {
  x: string,
  y: string,
  [key: PropertyKey]: unknown   //<--- type PropertyKey = string | number | symbol. A mapped type to accomodate additional non-required properties. We can constrain the 'unknown' here depending upon the context of use.
}

function applyFn(input: SomeRequired): void {

}

applyFn({}); // <-- Error, missing all required properties
applyFn({x: "1"}); // <-- Error, missing some of the required properties
applyFn({x: "1", y: "2"}); // <-- Ok, at least all required properties are there
applyFn({x: "1", y:"2", z: "3", p: { a: 1 }}); // Ok, additional properties along with the required ones

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

  • Related