简体   繁体   中英

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

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 ?

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

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

Use Partial<ParamType> . This allows you to specify only a subset of the type.

https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM