简体   繁体   English

在Typescript中作为函数参数类

[英]Class as function parameter in Typescript

In Angular 2 testing utility I do something like this: 在Angular 2测试实用程序中,我执行以下操作:

fixture = TestBed.createComponent(EditableValueComponent);

where EditableValueComponent is a normal component class. 其中EditableValueComponent是普通的组件类。

I wonder how it works: 我不知道它是如何工作的:

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

Beceause I wanna do something similar (I want to simplify some testing stuff): 因为我想做类似的事情(我想简化一些测试内容):

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

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

The problem is: 问题是:

'T' only refers to a type, but is being used as a value here.' “ T”仅指类型,但在此处被用作值。

EDIT #1 编辑#1

I solved the problem this way: 我这样解决了这个问题:

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

But I still don't know how it works.. 但我仍然不知道它是如何工作的。

You still need to pass actual class (constructor function that creates instances of a class) into constructor function of SuperFixture . 您仍然需要将实际的类(创建类实例的构造函数) SuperFixture构造函数。 Under the hood TestBed.createComponent calls provided constructor function with new to create instance of provided class. TestBed.createComponent调用提供的构造函数和new来创建提供的类的实例。 So SuperClass signature might look like this: 因此, 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;
  }
}

Was working on that answer, but had to step out for coffee. 正在努力解决这个问题,但不得不出门喝咖啡。 ¯_(ツ)_/¯ ¯_(ツ)_ /¯

The language feature you are using is called a Generic in TypeScript. 您使用的语言功能在TypeScript中称为“ 通用” It allows defining types at runtime with " type variables " (like <T> ), which are separate from function arguments. 它允许在运行时使用与函数参数分开的“ 类型变量 ”(如<T> )定义类型。

Before, the type variable was being passed as a function argument , when the function expected an instance of type T. That's what the error means. 以前,当函数需要类型T的实例时,将类型变量作为函数参数传递。这就是错误的含义。

The change you made works because you are passing the type variable and the instance in their correct positions in the call. 之所以进行更改,是因为您将类型变量和实例传递给它们在调用中的正确位置。

The SuperFixture object gets the value of T when you create it, and then it will pass that type variable to createComponent in the constructor, along with the value of component . SuperFixture对象在创建时会获取T的值,然后它将该类型变量以及component的值传递给构造函数中的createComponent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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