typescript - 过滤掉具有 null 或未定义属性的对象
问题描述
我正在使用 AWS 开发工具包,看起来它的很多对象都有未定义的成员。下面的示例适用于S3.Object
export interface Object {
/**
*
*/
Key?: ObjectKey;
/**
*
*/
LastModified?: LastModified;
/**
*
*/
ETag?: ETag;
/**
*
*/
Size?: Size;
/**
* The class of storage used to store the object.
*/
StorageClass?: ObjectStorageClass;
/**
*
*/
Owner?: Owner;
}
因此,在处理这些对象的列表时,我总是必须在函数顶部检查成员是否未定义。
objects.map(async (object) => {
if(object.Key) {
return
}
...
}
我尝试了以下但没有奏效:
const objects = objects.filter(object => object.Key)
但类型objects
仍然S3.Object
如此Key
。string|undefined
我也试过:
const objects: {Key: string}[] = objects.filter(object => object.Key)
但我收到以下错误:
Type 'Object[]' is not assignable to type '{ Key: string; }[]'.
Type 'Object' is not assignable to type '{ Key: string; }'.
Types of property 'Key' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'
有没有办法先通过这个属性过滤对象?我想在处理时删除对该属性的未定义检查objects
解决方案
您可以为此使用类型保护:
interface S3Object {
Key?: string;
}
interface MyObject {
Key: string;
}
function isValidObject(obj: S3Object): obj is MyObject {
return obj.Key !== undefined;
}
let objs1: S3Object[] = [{Key: ''}, {Key: 'test'}, {}, {}];
let objs2: MyObject[] = objs1.filter(isValidObject);
console.log(objs2);
这里isValidObject
可以在过滤器中使用,以使编译器知道过滤后的项目是 MyObject 类型。
当然,您可以删除MyObject
接口并替换为{Key: string}
推荐阅读
- python-3.x - 比较 2 个包含 IP 地址的文件并返回一个不常见的文件
- neo4j - 从 neo4、apoc、Cypher 访问地图值
- java - 关于我的音板 android 应用程序的内存问题的问题 (E/MediaPlayerNative: error (1, -19))
- apache - 如何使用 mod_rewrite 编写 SEO 友好的 url
- objective-c - 为什么找不到框架中的标题?
- javascript - 基于复选框状态在 JavaScript 中添加/删除表列
- excel - 在 Excel 中将列转置为行
- ios - 在 Realm Swift 中对列表进行排序
- c - 第二次 calloc 问题 - 在 C 上
- javascript - 快速排序问题 - 没有得到正确的结果