typescript - 如何更好地处理部分接口
问题描述
在下面的场景中,我不想信任不受信任的对象,并且想在对其进行操作之前检查每个字段是否真实。但是,使用 Partial 泛型时,它不会在尝试将字段传递给函数时推断该字段不是未定义的。有没有更好的方法来处理这个?
export interface IFoo {
id: number;
value: string;
}
export function DoBar(obj: IFoo) {
// do stuff
return;
}
const untrustedObj: Partial<IFoo> = { id: 1, value: 'test' };
if (untrustedObj.id && untrustedObj.value) {
DoBar(untrustedObj); // Error
}
错误:
Argument of type 'Partial<IFoo>' is not assignable to parameter of type 'IFoo'.
Types of property 'id' are incompatible.
Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts(2345)
解决方案
您可以编写一个类型保护函数来is
缩小对象的类型:
function hasKey<T, K extends keyof T>(obj: Partial<T>, key: K):
obj is Partial<T> & { [k in K]: T[k] }
{
return Object.prototype.hasOwnProperty.call(obj, key);
}
用法:
if(hasKey(untrustedObj, 'id') && hasKey(untrustedObj, 'value')) {
doBar(untrustedObj); // no type error
}
我已将其用作Object.prototype.hasOwnProperty
测试此问题的更通用解决方案,因为您可能想要检查布尔属性是否存在(而不是检查它是否为真)。
推荐阅读
- reactjs - 如何获取 React 表行数据 Onclick
- java - 如何将文本文件中的特定行放入数组列表中?
- ruby-on-rails-5 - 如何使用 Rails.application.credentials.dig 将数据加载到 storage.yml 短语?
- java - 从类路径中获取文件列表
- c# - 从插件加载具有相同 AssemblyVersion 的多个.net 程序集
- neuroscience - 如何获取 NeuroML 数据库中可用模型的完整列表?
- javascript - 为什么我不能在 Firefox Web 控制台中更改 `name` 的类型?
- python - 如何从 pyqtgraph TextItem 获取属性?
- php - 使用 rxjava 和改造从服务器获取响应
- javascript - DOMContentLoaded 在导航后未触发,但在使用 javascript_pack_tag 时在页面重新加载时触发