【问题标题】:Filtering out objects with null or undefined properties过滤掉具有 null 或未定义属性的对象
【发布时间】:2019-10-03 15:45:05
【问题描述】:

我正在使用 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时删除对该属性的未定义检查

【问题讨论】:

  • const validKeys = Object.keys(yourObject).filter(k => yourObject[k])
  • @boop_the_snoot 我不想获得有效的密钥。我不想检查属性是null 还是undefined,方法是将Object 类型的对象(使用Key: string|undefined)缩小为Object(使用Key: string),如果在检查后证明了Key 已定义。
  • 为 S3.Object 创建您自己的接口/类,其中键类型定义为数据类型,然后将 s3obj 转换为您的接口。喜欢:const mys3 = S3Obj as unknown as MyS3Obj.
  • 或者看看docs,你可以用这个

标签: typescript


【解决方案1】:

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

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}

Documentation 这个功能。

【讨论】:

  • 有点相关,有没有办法定义匿名类型S3Object with Key:string
  • 对应的类型是S3Object & {Key: string}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多