[英]TypeScript: check that the required properties of an argument are defined before passing it to a function call
This doesn't compile ( playground ): 这不会编译( 操场 ):
function myFunction(params: {
a: Date,
b?: Date
}) {
if (params.b) {
myFunctionInternal(params); // ERROR!
}
}
function myFunctionInternal(params: {
a: Date,
b: Date
}) {}
Is there a more elegant workaround than params as any
? 是否有比
params as any
更优雅的解决方法?
The problem is that the type guard impacts just the type of the field ( params.b
will have the undefined
removed) not the type of whole object ( param
will continue to have the type { a: Date, b?: Date }
) 问题在于类型防护仅影响字段的类型(
params.b
将删除undefined
),而不影响整个对象的类型( param
继续具有类型{ a: Date, b?: Date }
)
Not sure I would call it more elegant, but we can create a type guard that removes the undefined from a type field: 不知道我会说它更优雅,但是我们可以创建一个类型防护,从类型字段中删除未定义的类型:
type RemoveOptionalFromField<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> & { [P in K]-?: T[P] }
function notNull<T, K extends keyof T>(o: T | RemoveOptionalFromField<T, K>, key: K) : o is RemoveOptionalFromField<T, K> {
return !!o[key];
}
function myFunction(params: {
a: Date,
b?: Date
}) {
if (notNull(params, 'b')) {
params.b.getDate()
myFunctionInternal(params);
}
}
We could even create a version that takes any number of keys: 我们甚至可以创建一个使用任意数量键的版本:
function allNotNull<T, K extends keyof T>(o: T | RemoveOptionalFromField<T, K>, ...keys: K[]) : o is RemoveOptionalFromField<T, K> {
return keys.every(k => !!o[k]);
}
function myFunction(params: {
a?: Date,
b?: Date
}) {
if (allNotNull(params, 'b', 'a')) {
params.b.getDate()
myFunctionInternal(params);
}
}
the error message said property 'b' is optional in type '{ a: Date; 错误消息指出属性'b'在类型'{a中是可选的:日期; b?: Date;
b ?:日期; }' but required in type '{ a: Date;
}”,但在类型“ {{a:Date; b: Date;
b:日期; }'
}”
It can be solve like this 这样可以解决
myFunctionInternal(params as {a,b});
or 要么
myFunctionInternal({a:params.a ,b:params.b});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.