首页 > 解决方案 > 从对象中删除空值的打字稿完全类型化函数

问题描述

我正在尝试创建一个函数,该函数以完全类型化的方式从对象中删除任何空值。

我在这里尝试

type Results<T> = {
  [K in keyof T]: Exclude<T[K], null>
}

function stripNullParams<T>(obj: T): Partial<Results<T>> {
  const result: Partial<Results<T>> = {}
  Object.entries(obj).forEach(([k, v]) => {
    if (v !== null) {
      // this says: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Partial<Results<T>>'.
      // No index signature with a parameter of type 'string' was found on type 'Partial<Results<T>>'
      result[k] = v
      
    }
  })
  return result
}


const test = {
    fist_name: "test",
    last_name: "foo",
    company: null,
}

const res = stripNullParams(test)

但它似乎没有按预期工作。是否有可能在 Typescript 中实现这一点?

标签: typescripttypescript-typings

解决方案


使用前先施放钥匙。Object.entries() 故意返回一个模棱两可的键类型,而不是因为typescriptkeyof T不保证除了在T

function stripNullParams<T>(obj: T): Partial<Results<T>> {
  const result: Partial<Results<T>> = {}
  Object.entries(obj).forEach(([k, v]) => {
    if (v !== null) {
      result[k as (keyof T)] = v
    }
  })
  return result
}

推荐阅读