首页 > 解决方案 > 过滤掉具有 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如此Keystring|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

标签: typescript

解决方案


您可以为此使用类型保护:

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}

此功能的文档


推荐阅读