0
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

我需要分配inputdbDataage属性上的类型不兼容。

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 }

有什么建议么?谢谢。

4

1 回答 1

-1

使用这个,但如果你想替换所有对象值,传播它并使用removeNull(value)withlodash

function removeNull<T>(data: T | null | undefined) {
  if (isNull(data)) return undefined;
  return data
}

没有lodash

function removeNull<T>(data: T | null | undefined) {
  if (typeof data === null) return undefined;
  return data
}
于 2021-10-06T04:15:29.890 回答