TypeScript type annotation don't exists in the runtime, also instanceof
operator works only with prototypes, it means that you need to have custom prototype in the object to work with this operator (use function constructor or ES6 Class).
BookModel
is plain object, there is no additional prototype to check (outside object prototype). That is why you cannot use instanceof, and as said before BookModel
as a type cannot be used as a runtime value.
What we can use instead is type representation - the data structure. To differentiate BookModel
from PostModel
we need to find what props are different, find the discriminant. If you don't have any special property which differs between
BookModel
and PostModel
, such can be created. Below I have used _type
:
export interface BookModel {
_type: 'Book', // special meta information as discriminant
id: number;
title: string;
publishedAt: Date;
}
export interface PostModel {
_type: 'Post',// special meta information as discriminant
id: number;
title: string;
publishedAt: Date;
}
// below I removed first argument for readability
// check also that resource is now specified as a union type
function validate(resource: BookModel | PostModel) : boolean {
if (resource._type === 'Book') {
// here Book
}
if (resource._type === 'Post') {
// here Post
}
return false;
}
let book: BookModel = { id: 1, title: "Title", publishedAt: new Date(2018, 10, 12), _type: 'Book' }
let valid = validate(book);
Thanks to _type
we can apply custom logic by differentiate between structure representing specific types.