[TypeScript] instanceof and Type Guards (getPrototypeOf)
typescript and type instanceof
2023-09-14 08:59:13 时间
class Foo { bar() {} } const bar = new Foo() console.log(bar instanceof Foo) // true console.log(Object.getPrototypeOf(bar) === Foo.prototype) // true
class Song { constructor(public title: string, public duration: number) { } } class Playlist { constructor(public name: string, public songs: Song[]) { } } function getItemName(item: Song | Playlist) { if (item instanceof Song) { return item.title; } return item.name; } const songName = getItemName(new Song('Wonderful Wonderful', 300000)); console.log('Song name:', songName); const playlistName = getItemName( new Playlist('The Best Songs', [new Song('The Man', 300000)]) ); console.log('Playlist name:', playlistName);
相关文章
- 计算时间差工具类(TypeScript/JavaScript)
- typescript 多继承_说明类的继承和多态有什么作用
- Typescript教程_安装typescript
- TypeScript基础常用知识点总结
- TypeScript基础知识
- Typescript 4.9重点特性探索
- 一旦你学习了typescript,你就再也放不下了
- Vue 3 + Typescript + Vite 基个人网站二维码登录功能
- typescript 中的时间处理
- TypeScript方法装饰器应用
- (一)为什么要使用 TypeScript(二)安装并配置 Ts
- MySQL中AND的使用方法及含义解析(mysql中and的含义)
- Mysql中强大的AND运算符的使用方法探究(mysql中and的使用)
- Oracle中使用除了And的其他查询关键字(oracle中除了and)
- and的区别Oracle数据库中的OR与AND的差异(oracle中or和)
- Oracle中使用AND运算符的示例分析(oracle中and用法)