我只是在VisualStudio 2012中测试打字稿并且其类型系统有问题。我的html网站有一个带有idmycanvas的canvas标签。我正试图在这个画布上画一个矩形。这是代码
I'm just testing typescript in VisualStudio 2012 and have a problem with its type system. My html site has a canvas tag with the id "mycanvas". I'm trying to draw a rectangle on this canvas. Here's the code
var canvas = document.getElementById("mycanvas"); var ctx: CanvasRenderingContext2D = canvas.getContext("2d"); ctx.fillStyle = "#00FF00"; ctx.fillRect(0, 0, 100, 100);不幸的是,VisualStudio抱怨
Unfortunately VisualStudio complains that
属性'getContext'在'HTMLElement'的价值上不存在
the property 'getContext' does no exist on value of type 'HTMLElement'
它标志着第二行作为错误。我认为这只是一个警告,但代码不编译。 VisualStudio说
It marks the second line as an error. I thought this would be merely a warning but the code does not compile. VisualStudio says that
存在构建错误。你想继续并运行最后的成功构建吗?
there were build errors. Would you like to continue and run the last successful build ?
我根本不喜欢这个错误。为什么没有动态方法调用?毕竟方法getContext肯定存在于我的canvas元素上。但是我认为这个问题很容易解决。我刚刚为canvas添加了一个类型注释:
I didn't like this error at all. Why is there no dynamic method invocation ? After all the method getContext definitely exists on my canvas element. However I thought this problem would be easy to solve. I just added a type annotiation for canvas:
var canvas : HTMLCanvasElement = document.getElementById("mycanvas"); var ctx: CanvasRenderingContext2D = canvas.getContext("2d"); ctx.fillStyle = "#00FF00"; ctx.fillRect(0, 0, 100, 100);但类型系统仍然不满意。这是新的错误消息,这次是在第一行:
But the type system still wasn't satisfied. Here's the new error message, this time in the first line:
无法将'HTMLElement'转换为'HTMLCanvasElement':输入 'HTMLElement'缺少属性'toDataURL',类型为'HTMLCanvasElement'
Cannot convert 'HTMLElement' to 'HTMLCanvasElement': Type 'HTMLElement' is missing property 'toDataURL' from type 'HTMLCanvasElement'
嗯,我全力以赴静止打字,但这使语言无法使用。类型系统要我做什么?
Well, I'm all out for static typing but this makes the language unusable. What does the type system want me to do ?
更新:
Typescript确实不支持动态调用我的问题可以通过类型转换来解决。我的问题基本上是这一个的重复 TypeScript:cast HTMLElement
Typescript has indeed no support for dynamic invocation and my problem can be solved with typecasts. My question is basically a duplicate of this one TypeScript: casting HTMLElement
推荐答案var canvas = <HTMLCanvasElement> document.getElementById("mycanvas"); var ctx = canvas.getContext("2d");
或使用任何类型的动态查询(没有类型检查):
or using dynamic lookup with the any type (no typechecking):
var canvas : any = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d");您可以在 lib.d.ts 。
更多推荐
TypeScript:类型系统的问题
发布评论