Use the $schema
property to narrow down the type of the metadata:
const metadata: PostMetadata = ...
if (metadata.$schema === PostSchemaId.ARTICLE_LATEST) {
// metadata is ArticleMetadata
metadata.content; // => always string, not undefined
}
Use the $schema
property to determine the type of the metadata in an exhaustive switch statement:
const metadata: PostMetadata = ...
switch (metadata.$schema) {
case PostSchemaId.ARTICLE_LATEST:
// metadata is ArticleMetadata
break;
case PostSchemaId.AUDIO_LATEST:
// metadata is AudioMetadata
break;
case PostSchemaId.IMAGE_LATEST:
// metadata is ImageMetadata
break;
case PostSchemaId.TEXT_ONLY_LATEST:
// metadata is TextOnlyMetadata
break;
// ...
}
PostMetadata
is a discriminated union of all possible post metadata types.