type GraphQLInput = {
email: string;
age?: null | number | undefined;
height?: null | number | undefined;
}
type PrismaPerson = {
email: string;
age: number | undefined;
height: null | number;
}
let input: GraphQLInput = {
email: "some@email.com",
height: null
}
let dbData: PrismaPerson = input
我需要分配input
给dbData
但age
属性上的类型不兼容。
let dbData: PrismaPerson
Type 'GraphQLInput' is not assignable to type 'PrismaPerson'.
Types of property 'age' are incompatible.
Type 'number | null | undefined' is not assignable to type 'number | undefined'.
Type 'null' is not assignable to type 'number | undefined'.
我尝试清除所有null
值,undefined
但我不知道如何仅在不可分配类型的情况下更改它。
function cleanNullToUndefined(obj: any): any {
if (obj === null) {
return undefined;
}
if (typeof obj !== 'object') {
return obj;
}
return Object.keys(obj).reduce((result, key) => ({
...result,
[key]: cleanNullToUndefined(obj[key])
}), {});
}
let dbData: PrismaPerson = cleanNullToUndefined(input)
console.log(dbData)
// { email: 'some@email.com', height: undefined }
我的预期结果{ email: 'some@email.com', height: null }
是{ email: 'some@email.com', height: undefined }
有什么建议么?谢谢。