简体   繁体   English

打字稿泛型?

[英]Typescript generics?

I am attempting to write a directive in typescript to display a table of items. 我正在尝试在打字稿中编写指令以显示项目表。 The model I am using is something like this: 我正在使用的模型是这样的:

export class Base implements IBase {
    prop1: number;
    prop2: string;
}

export class Concrete extends Base implements IConcrete {
    prop3: number;
    prop4: number;
}

How could I write a directive that takes the Base class and display a list of items. 我如何编写一个使用Base类并显示项目列表的指令。 Basically I want a generic directive that I can use to display a list of any object that extends the Base class. 基本上,我想要一个通用指令,可以用来显示扩展Base类的任何对象的列表。

that I can use to display a list of any object that extends the Base class. 我可以用来显示扩展Base类的任何对象的列表。

You can sepecify a generic constraint using extends . 您可以使用extends分隔通用约束。 Eg the following function: 例如以下功能:

function Foo<T extends Base>(base:T){}

Will accept any base variable as long as it conforms to the structural contract offered by Base (because of T extends Base ) 只要符合Base提供的结构合同,就将接受任何base变量(因为T extends Base

How could I write a directive that takes the Base class and display a list of items 我如何编写一个接受Base类并显示项目列表的指令

In the following example Displayable would be like "Base" and "TextValue" could be one such class that implements it. 在下面的示例中,Displayable就像“ Base”,“ TextValue”可以是实现它的此类。 This is a simple example that uses Angular2 -- can't vouch for how conventional it is since I don't write much Angular2. 这是一个使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM