簡體   English   中英

在Typescript中作為函數參數類

[英]Class as function parameter in Typescript

在Angular 2測試實用程序中,我執行以下操作:

fixture = TestBed.createComponent(EditableValueComponent);

其中EditableValueComponent是普通的組件類。

我不知道它是如何工作的:

static createComponent<T>(component: Type<T>): ComponentFixture<T>;

因為我想做類似的事情(我想簡化一些測試內容):

export class SuperFixture<T>
{  
    fixture: ComponentFixture<T>;
    component: T;

    constructor()
    {         
        this.fixture = TestBed.createComponent(T); // <--- problem here!
        this.component = this.fixture.componentInstance;   
    }
}

問題是:

“ T”僅指類型,但在此處被用作值。

編輯#1

我這樣解決了這個問題:

constructor(component)
{
    this.fixture = TestBed.createComponent<T>(component);

但我仍然不知道它是如何工作的。

您仍然需要將實際的類(創建類實例的構造函數) SuperFixture構造函數。 TestBed.createComponent調用提供的構造函數和new來創建提供的類的實例。 因此, SuperClass簽名可能如下所示:

class SuperFixture<T>
{
  fixture: ComponentFixture<T>;
  component: T;

  // passing in the constructor for instances of T
  constructor(componentConstructor: new () => T)
  {
    this.fixture = TestBed.createComponent<T>(componentConstructor);
    this.component = this.fixture.componentInstance;
  }
}

正在努力解決這個問題,但不得不出門喝咖啡。 ¯_(ツ)_ /¯

您使用的語言功能在TypeScript中稱為“ 通用” 它允許在運行時使用與函數參數分開的“ 類型變量 ”(如<T> )定義類型。

以前,當函數需要類型T的實例時,將類型變量作為函數參數傳遞。這就是錯誤的含義。

之所以進行更改,是因為您將類型變量和實例傳遞給它們在調用中的正確位置。

SuperFixture對象在創建時會獲取T的值,然后它將該類型變量以及component的值傳遞給構造函數中的createComponent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM