我想在类中调用一个特定的函数,但只允许调用该函数,前提是当前设置了可为空的属性。
我拥有的代码如下:
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
}
}我希望上面的代码能让你明白这一点。我想告诉'draw_image‘函数,只有在当前设置了this.image时才能调用它。
let visual = new VisualComponent(p.color(0,0,255));
visual.draw(); // <-- draws the color
visual.image = __some_image__;
visual.draw(); // <-- draws the image所以我假设我需要一些类似如下的typeguards:Keep track of state in class instance
type VisualComponentWithImage = VisualComponent & {image:p5.Image};
class VisualComponent {
...
public has_image(): this is VisualComponentWithImage {
if (this.image) return true;
return false;
}
// well, now I can use the typeguard here but the 'draw_image' function
// is still not narrowed down obviously
public draw(p:p5) {
if (this.has_image()) {
this.draw_image(p);
} else {
p.fill(this.fallback_color);
p.rect(0,0,100,100);
}
}
// I expect now to do the following
private draw_image(p:p5) : this if VisualComponentWithImage {
// and in here this should be of type VisualComponentWithImage
// as well as any call to this prior to asserting that image exists should be a type error
}
...
}我在Typescript文档中做了一些尝试:
https://www.typescriptlang.org/docs/handbook/utility-types.html
我认为ThisType<T>可能是正确的方向,但是我不知道如何在已经存在的类上下文中使用它。(它似乎用于示例中动态创建的类)
在我看来,https://www.typescriptlang.org/docs/handbook/decorators.html装饰者似乎可以解决这个问题。但老实说,它们看起来有点吓人,使用起来也不是很整洁。整洁毕竟是我想要的。
我目前的解决方案是将'draw_image‘函数从类中分离出来,如下所示:
function draw_image(this: VisualComponentWithAnimation, p:p5) {
p.drawImage(p);
}我在'draw‘函数中这样调用它
if (this.has_image()) {
draw_image(this, p);
}虽然理想情况下,我希望将该函数放在类中,只是为了让它属于它。
发布于 2020-09-14 06:51:40
就在提出问题的过程中,a有了解决的想法。或者更确切地说,我尝试了一些愚蠢的东西,结果证明是有效的。
我只是在类中移动了draw_image(this: VisualComponentWithAnimation, p:p5) ...,仅此而已。
我从来没有想过我可以在一个类中像这样‘覆盖’this。但它完美地缩小了函数内部的'this‘范围,像任何其他类方法图像一样被调用(没有显式地放入"this"),并且如果没有设置’this.draw_image(p);‘,也不允许调用。
我猜有时写一篇文章也有助于解决一个问题。
https://stackoverflow.com/questions/63876251
复制相似问题