[英]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.我有一个 util function,它的第一个参数
param
必须包括(例如简化)属性param.X
和param.Y
,但它有什么其他属性并不重要。 For instance it can also have param.Z
but that's not used by the util function and can be ignored.例如,它也可以有
param.Z
但它没有被 util function 使用,可以忽略。
How can I type the param such that it enforces this constraint without complaining something like ParamType does not include property Z
?我如何键入参数以使其强制执行此约束而不抱怨诸如
ParamType does not include property Z
?
Intersect the object type with Record<PropertyKey, unknown>
.将 object 类型与
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>
.使用
Partial<ParamType>
。 This allows you to specify only a subset of the type.这允许您仅指定类型的一个子集。
https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.