typescript 如何在具有类型安全性的同一组件上实现 OnInit 和 OnChanges

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38185591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:37:19  来源:igfitidea点击:

How to implement OnInit and OnChanges on same component with type safety

typescriptangular

提问by hholtij

One of the things I like about typescript is its type safety and I use it consistently.

我喜欢打字稿的一件事是它的类型安全,我一直在使用它。

Typescript does not support multiple inheritance, so how can I extend an Angular 2 component class by OnInitand OnChangesat the same time?

打字稿不支持多重继承,所以我怎么能由延长的2个组件类OnInit,并OnChanges在同一时间?

I know that it works without declaring the inheritance but I like my code without squiggly lines.

我知道它可以在不声明继承的情况下工作,但我喜欢我的代码没有波浪线。

回答by Blackus

OnInitand OnChangesare not classes but interfaces, so your components don't inherit but implementthose interfaces.

OnInit并且OnChanges不是类而是接口,因此您的组件不会继承而是实现这些接口。

As a class can implements as many interfaces as it needs, there is no problem implementing both OnInitand OnChangesinterfaces on the same component.

由于一个类可以实现任意数量的接口,因此在同一个组件上实现OnInitOnChanges接口没有问题。

For example:

例如:

class FooComponent implements OnInit, OnChanges {
}

For more information, have a look at Angular Lifecycle Hooks guide.

有关更多信息,请查看Angular Lifecycle Hooks 指南