My current situation involves using the AWS SDK, and I've noticed that many of its objects have members that can be undefined. Take for example 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;
}
During the processing of a list of these objects, I always need to check if the member is not undefined at the beginning of the function:
objects.map(async (object) => {
if(object.Key) {
return
}
...
}
I attempted the following approach, but it didn't provide the desired outcome:
const objects = objects.filter(object => object.Key)
Unfortunately, even after this operation, the type of objects
remains as S3.Object
, keeping Key
as string|undefined
.
I also experimented with:
const objects: {Key: string}[] = objects.filter(object => object.Key)
However, I encountered the following error message:
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'
Is there a better way to initially filter the objects based on this property? My goal is to avoid the constant checking for undefined whenever working with objects
.