I'm trying to cast an object (the Item interface) to it's derived interface (FileItem or FolderItem)
interface Item {
id: number;
name: string;
}
interface FileItem extends Item {
size: number;
}
interface FolderItem extends Item {
parent_id: number;
}
const files: FileItem[] = [ {id: 1, name: 'file name 1', size: 1024 } ];
const folders: FolderItem[] = [ {id:1, name: 'folder 1', parent_id: 0} ];
const items = new Array<Item>(...files, ...folders);
items.forEach(i => {
const isFile = i as FileItem;
if (isFile) {
writeLog('its a file');
}
else writeLog('its a folder');
})
in the foreach loop, typescript cast all items to a FileItem which is wrong, because it should cast to FileItem and FolderItem, take a look at the demo
is this the way typecasting in typescript works? how to cast to the proper interface.