[英]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.