【问题标题】:Typescript return object without null or undefined values打字稿返回没有空值或未定义值的对象
【发布时间】:2021-12-16 13:17:24
【问题描述】:

我们在代码库中使用cleanNullOrUndefined 函数,如果键的值为空或未定义,它会删除对象中的键。这不是很好的类型,只是返回原始对象的Partial,这会在其他地方给出一些错误。

我们需要输入函数以返回对象,删除 null 或未定义的键并推断其他键的类型。

例子:

const obj = {
  a: 1,
  b: 'string',
  c: false,
  d: null,
  e: undefined
}

// Desired return type

interface ReturnType {
  a: number,
  b: string,
  c: boolean
}

我似乎无法理解如何做到这一点。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    考虑这个例子:

    const obj = {
      a: 1,
      b: 'string',
      c: false,
      d: null,
      e: undefined
    }
    
    type Validate<T> = Pick<T, {
      [Prop in keyof T]: T[Prop] extends null | undefined ? never : Prop
    }[keyof T]>
    
    // type Test = {
    //     a: 1;
    //     b: 'string';
    //     c: false;
    // }
    type Test = Validate<{
      a: 1,
      b: 'string',
      c: false,
      d: null,
      e: undefined
    }>
    
    const util = <Obj,>(obj: Obj): Validate<Obj> => {
      return 'NOT IMPLEMENTED' as any
    }
    const result = util({
      a: 1,
      b: 'string',
      c: false,
      d: null,
      e: undefined
    })
    
    result.a // ok
    result.e // error
    

    Playground

    Validate 遍历每个对象键并检查它是否扩展了null | undefined。如果是 - 返回never,否则 - 返回密钥名称Prop[keyof T] - 并从新创建的对象中获取所有值。 Pick - 反过来又只从T 获得有效密钥。

    【讨论】:

    • Yossarian 先生一如既往的出色回答,谢谢。
    • @AndréKrosby 谢谢!
    【解决方案2】:

    以下可能是答案的一半。我想表明您只需一行(链)代码即可获得目标对象:

    const obj = {
      a: 1,
      b: 'string',
      c: false,
      d: null,
      e: undefined
    };
    
    const dest = Object.keys(obj)
        .filter(a => obj[a] !== null && obj[a] !== undefined)
        .reduce((c, a) => { c[a] = obj[a]; return c; }, {});
    
    console.log(dest);

    但可能还有更多,只是为了正确推断结果类型。问题是——你真的需要它吗? ;)

    【讨论】:

      猜你喜欢
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      相关资源
      最近更新 更多