有没有办法将“成员变量”定义为“扩展对象”而不是静态类型(不使用接口)?
就像这个伪代码:
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;
}
这样我可以在不获取类型错误的情况下添加未在基类或接口上定义的属性,但也可以从基类获取代码完成。嘿, lazy 严格打字?
答案 0 :(得分:0)
考虑约束泛型类型参数。
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
答案 1 :(得分:0)
我不完全确定我理解你,但如果是这样,那么就是这样:
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() {}
}
}
}
答案 2 :(得分:0)
交叉类型
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() {
}
}
}