【发布时间】: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