[英]Typescript generics?
我正在嘗試在打字稿中編寫指令以顯示項目表。 我正在使用的模型是這樣的:
export class Base implements IBase {
prop1: number;
prop2: string;
}
export class Concrete extends Base implements IConcrete {
prop3: number;
prop4: number;
}
我如何編寫一個使用Base類並顯示項目列表的指令。 基本上,我想要一個通用指令,可以用來顯示擴展Base類的任何對象的列表。
我可以用來顯示擴展Base類的任何對象的列表。
您可以使用extends
分隔通用約束。 例如以下功能:
function Foo<T extends Base>(base:T){}
只要符合Base
提供的結構合同,就將接受任何base
變量(因為T extends Base
)
我如何編寫一個接受Base類並顯示項目列表的指令
在下面的示例中,Displayable就像“ Base”,“ TextValue”可以是實現它的此類。 這是一個使用Angular2的簡單示例-由於我沒有編寫太多Angular2,因此無法保證它的常規性。
import {Component, Input, ViewChild} from 'angular2/core';
interface Displayable {
displayValue: string;
}
class TextValue implements Displayable {
get displayValue() { return this.value; }
constructor(private value: string) { }
}
@Component({
selector: 'list-thing',
template: `
<h2>{{title}}</h2>
<ul>
<li *ngFor="#input of list">
{{input.displayValue}}
</li>
</ul>
`
})
export class OtherAppComponent<T extends Displayable> {
@Input() title: string;
private list: T[] = [];
addToList(item: T): void {
console.log('adding', item.displayValue)
this.list.push(item);
}
}
@Component({
selector: 'my-app',
template: `
<input #box (keyup.enter)="entered(box.value)">
<list-thing title='stuff you inputted'>
</list-thing>
`,
directives: [OtherAppComponent]
})
export class AppComponent {
@ViewChild(OtherAppComponent) listthing: OtherAppComponent<TextValue>;
constructor() {
}
value: string;
entered(valueEntered) {
this.listthing.addToList(new TextValue(valueEntered));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.