Typescript 在方法中缩小此方法的特定成员范围
我想在类中调用一个特定的函数,但只允许在当前设置了可空属性的情况下调用该函数Typescript 在方法中缩小此方法的特定成员范围,typescript,typescript-typings,Typescript,Typescript Typings,我想在类中调用一个特定的函数,但只允许在当前设置了可空属性的情况下调用该函数 let visual = new VisualComponent(p.color(0,0,255)); visual.draw(); // <-- draws the color visual.image = __some_image__; visual.draw(); // <-- draws the image 我的守则如下: class VisualComponent { public fall
let visual = new VisualComponent(p.color(0,0,255));
visual.draw(); // <-- draws the color
visual.image = __some_image__;
visual.draw(); // <-- draws the image
我的守则如下:
class VisualComponent {
public fallback_color: p5.Color;
public image: p5.Image | null = null;
public constructor(color:p5.Color) {
this.fallback_color = color;
}
public draw(p:p5) {
if (this.image) {
this.draw_image(p);
} else {
p.fill(this.fallback_color);
p.rect(0,0,100,100);
}
}
private draw_image(p:p5) {
// this has potentially a bit more logic in it or
// is different in subclasses
p.drawImage(this.image); // <-- Error this.image is possibly null
}
}
我在Typescript文档中进行了一些冒险:
我认为ThisType
可能是正确的方向,但我不知道如何在已经存在的类上下文中使用它。
(在示例中,它似乎用于动态创建的类)
在我看来,装饰师似乎能解决这个问题。
但老实说,它们看起来有点吓人,使用起来也不太整洁。
整洁毕竟是我想要的
我目前的解决方案是将“draw_image”函数与类分离,如下所示:
function draw_image(this: VisualComponentWithAnimation, p:p5) {
p.drawImage(p);
}
我在“draw”函数中这样调用它
if (this.has_image()) {
draw_image(this, p);
}
理想情况下,虽然我希望在类中具有该函数,但只要它属于它就可以了。就在制定问题的过程中,a有了解决问题的想法。 或者更确切地说,我尝试了一些愚蠢的事情,结果证明是有效的 我只是简单地移动了鼠标
draw_image(这是带有动画的VisualComponent,p:p5)代码>
在课堂上,就是这样
我从未想过我可以在类中像那样“重写”这个
。
但它完美地缩小了函数内部的“this”,
像任何其他类方法一样调用this.draw\u image(p)代码>
(没有明确地输入“this”),如果没有设置“image”,也不允许调用
有时写一篇文章也有助于解决问题
if (this.has_image()) {
draw_image(this, p);
}