如何在TypeScript中声明成员变量为扩展类型
how to declare member variable as extended type in TypeScript?
是否有办法将"成员变量"定义为"扩展对象"而不是静态类型(不使用接口)?
就像这样的伪代码:
class Foo {
bar -> extends Rectangle;
constructor(barInstance:IRectangle){
this.bar = barInstance;
this.bar.getArea(); //<-- is code completed because interface IRectangle
// no type error
this.bar.someCustomFunction = function() {
}
}
}
代替
class Foo {
bar: IRectangle;
//or
bar:Rectangle;
}
这样,我可以添加没有在基类或接口上定义的属性而不会出现类型错误,而且还可以从基类获得代码完成。嘿,懒惰严格类型?
交集类型
interface IRectangle {
getArea: () => number;
}
class Foo {
bar: IRectangle & { [key: string]: any; };
constructor(barInstance:IRectangle){
this.bar = barInstance;
this.bar.getArea(); //<-- is code completed because interface IRectangle
// no type error
this.bar.someCustomFunction = function() {
}
}
}
考虑一个受约束的泛型类型参数
interface Base {
prop: number;
}
interface Child extends Base {
thing: string;
}
class Foo<T extends Base> {
bar: T
}
var foo = new Foo<Child>();
foo.bar.thing; // now permitted by the type checker
我不确定我是否完全理解你的意思,但如果是的话,那么像这样:
interface IRectangle {
getArea(): void;
}
class Rectangle implements IRectangle {
getArea(): void {}
someCustomFunction(): void {}
}
class Foo<T extends IRectangle> {
bar: T;
constructor(barInstance: T){
this.bar = barInstance;
this.bar.getArea();
// no type error
if (this.bar instanceof Rectangle) {
(this.bar as any as Rectangle).someCustomFunction = function() {}
}
}
}
(code in playground)
相关文章:
- Chrome扩展:Can't从chrome.local变量中检索值
- Chrome扩展:是否有一种方法可以运行JavaScript来获取页面上的内部html,并将其保存到扩展中的变量中
- 将变量从扩展哈巴狗/玉模板传递到基本布局
- 如何从 Chrome 扩展程序中的内容脚本中获取变量
- 如何使用Javascript扩展对象'的原型使用声明中的变量
- Chrome扩展:storage.set()不接受变量作为关键字
- 使用Chrome扩展从以前的选项卡中获取变量
- Chrome扩展全局变量怪异
- 将变量传递到Chrome扩展中的徽章文本
- 在HTML中扩展JavaScript变量
- 如何在没有临时变量的情况下扩展方法(猴子补丁)
- 简单的一个?将变量从 Chrome 扩展程序页面传递到 PHP 页面
- JQuery:创建扩展返回变量未定义
- 是否可以在使用电子商务扩展时将自定义变量发送到谷歌分析
- Chrome扩展JSONP请求访问全局变量
- 如何在 chrome 扩展程序中重新加载浏览器后保留变量的值
- 在回调节点.js中扩展变量
- 保存和访问 API 会导致 Chrome 扩展程序中出现一个变量
- 将函数/变量从 chrome 扩展程序注入到页面
- 引导程序中的全局变量.js在 Firefox for Android 扩展中