Typescript从对象中剥离null值的完全类型化函数



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

我在这里尝试

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中实现这一点吗?

在使用键之前强制转换键。Object.entries((有意返回一个不明确的键类型,而不是keyof T,因为typescript不能保证除了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
}

最新更新