typescript - 从对象中删除空值的打字稿完全类型化函数
问题描述
我正在尝试创建一个函数,该函数以完全类型化的方式从对象中删除任何空值。
我在这里尝试
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() 故意返回一个模棱两可的键类型,而不是因为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
}
推荐阅读
- react-native - react-native-linear-gradient中的块颜色?
- powershell - 启动 Windows 应用程序并自动输入用户名和密码
- xamarin - 按钮上的 Xamarin.Forms 单击打开带有项目列表的弹出窗口
- python - url 超出最大重试次数:/ 由 ProxyError 引起
- python - 使用 pytorch 在张量中重新排列数据时保持梯度
- linux - Windows 病毒可以访问另一个系统的虚拟磁盘吗?
- sql-server - 使用 mssql-scripter 编写删除/创建数据库对象和数据的脚本时不要删除和创建数据库
- python - 使数组中的每个元素,本身就是一个数组
- node.js - 在特定路径中初始化 ApolloServer
- definition - Isabelle 中的多项式评估