您可以在实现另一个接口的组件的接口中键入字段吗?

时间:2019-09-12 10:51:56

标签: angular typescript interface components

我已经为我的组件创建了一个接口,以使为此类型创建的每个组件都具有相同的字段。然后,我有了另一个接口,该接口的字段需要这种类型的组件。

我已经创建了这些接口并设置了相应的组件和对象,但仍然出现以下错误:

Type 'typeof MyComponent' cannot be assigned to type 'ComponentShouldImplementThis<T>'. Property 'someField' is missing in type 'typeof MyComponent'.

我的界面

export interface ComponentShouldImplementThis<T> {
  someField: string;
}

export interface ContainsFieldComponentInterface<T> {
  component: ComponentShouldImplementThis<T>;
}

我的组件:

@Component({
 selector: 'mycomponent',
 template: '<div>Hello</div>'
})
export class MyComponent implements ComponentShouldImplementThis<any> {
  someField: string;
  constructor(){}
}

我对我大吼的对象:

let implementedInterface: ContainsFieldComponentInterface = {
  component: MyComponent
}

someField在实现ComponentShouldImplementThis时满足IDE,但是不喜欢用于实现它的组件的接口。

我要进行角度编译的东西是在做一个组件实例:

let implementedInterface: ContainsFieldComponentInterface = {
  component: new MyComponent
}

但这会导致其他一些下游问题。这是正确的实现吗?不知道我要去哪里错了。

1 个答案:

答案 0 :(得分:0)

fold<T>(T initialValue, T combine(T previousValue, E element)) → T 中有一个类型表示Component: https://angular.io/api/core/Type

用法:

class Product {
  final String name;
  final double price;

  Product({this.name, this.price});
}

List<Product> products = [
  Product(name: 'prod1', price: 100.0),
  Product(name: 'prod2', price: 300.0),
];

void main() {
  var sum = products.fold(0, (sum, next) => sum + next.price);
  print(sum);
}

为什么您的类型信息不起作用?您可能还记得JS / TS中的类是创建对象的函数(或构造函数)。您可以在界面中指定创建对象的类型(验证创建的对象将具有类的所有属性)。如果要缩小可能的构造函数,则必须创建另一种类型:

def start(self):
    self._server = asyncio.start_server(self._handle_client, self._ip, int(self._port), loop=self._loop)
    self._loop.create_task(self._server)

此签名意味着调用@property def port(self): if self._server is None: return None return self._server.sockets[0].getsockname()[1] 类型的函数将返回类型 return self._server.sockets[0].getsockname()[1] AttributeError: 'generator' object has no attribute 'sockets'

所以您的界面最终看起来像:

angular/core

但与使用export interface ContainsFieldComponentInterface<T> { component: Type<ComponentShouldImplementThis<T>>; } 的{​​{1}}

相同