我對 Angular 2 中的模型有疑問。我有 2 個模型:
interface Model1 {
id: number;
name: string;
size: string;
count: number;
children: Model2[];
}
interface Model2 {
id: number;
parentId: number
title: string;
subtitle: string;
publisher: string;
}
我通過 id 將一些資料與變數系結,但在某些情況下我使用 Model1,有時使用 Model2。如果我試圖用 2 個模型宣告它但它不起作用。有沒有辦法做到這一點而不是使用“任何”?我嘗試做這樣的事情:
private exampleVaraible: Model1 || Model2;
uj5u.com熱心網友回復:
宣告具有兩種型別定義的變數的正確語法是:
私有示例變數:Model1 | 模型2;
this.exampleVaraible 現在可以被賦值
this.exampleVaraible = { id: 12121, subtitle: '232323', parentId: 2323, publisher: '2323', title: '2323' };
this.exampleVaraible = { id: 1121212, name: '22323', size: '2323', count: 2323, children: [ { id: 12121, subtitle: '232323', parentId: 2323, publisher: '2323', title :'2323'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510211.html
