【发布时间】:2019-09-25 22:59:33
【问题描述】:
故事
我正在使用konva library 和 Typescript,它是 HTML5 Canvas JavaScript 框架。
这是一个简单的教程代码,我将其从 javascript 更改为 typescript。
import Konva from "konva";
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
const layer = new Konva.Layer();
stage.add(layer);
const box = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strockWidth: 4,
draggable: true
});
layer.add(box);
但我的 Visual Studio 代码显示如下错误消息。
Argument of type 'Rect' is not assignable to parameter of type 'Group | Shape<ShapeConfig>'.
Type 'Rect' is not assignable to type 'Shape<ShapeConfig>'.
Types of property 'hitFunc' are incompatible.
Type 'GetSet<(ctx: Context, shape: Rect) => void, Rect>' is not assignable to type 'GetSet<(ctx: Context, shape: Shape<ShapeConfig>) => void, Shape<ShapeConfig>>'.
Type '(ctx: Context, shape: Rect) => void' is not assignable to type '(ctx: Context, shape: Shape<ShapeConfig>) => void'.
Types of parameters 'shape' and 'shape' are incompatible.
Type 'Shape<ShapeConfig>' is missing the following properties from type 'Rect': _sceneFunc, cornerRadiusts(2345)
Shape 类在 Shape.d.ts 中,Rect 在 Rect.d.ts 中。
我可以看到Rect 扩展了Shape!但 VSC 显示错误。
如果我将Rect.d.ts 中的两个属性添加到Shape 类中,
错误消失了。
export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Node<Config> {
_sceneFunc(context: any): void; // this was in Rect class
cornerRadius: GetSet<number, this>; // this was in Rect class
...
...
问题
我知道layer.add() 函数只接受Shape 类型。但如您所知,Typescript 允许像下面这样向下转换。
class Base {
baseProperty: string = "aaaa";
}
class A extends Base {
aProperty: number = 1;
}
var a: A = new A();
function test(arg: Base) {
console.log(arg.baseProperty);
}
test(a); // => No Error
我不明白为什么 layer.add() 不能接受 Rect 类型,即使它扩展了 Shape 类型。我错过了什么?
我需要你的建议。 谢谢。
【问题讨论】:
-
你试过 layer.add(
box) 吗? -
@CharybdeBE 错误:
Conversion of type 'Rect' to type 'Shape<ShapeConfig>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
标签: typescript konvajs