[英]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 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() {}
}
}
}
( 操场上的代码 )
交叉点类型
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() {
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.