TypeScript:类型系统的问题

编程入门 行业动态 更新时间:2024-10-24 04:37:31
本文介绍了TypeScript:类型系统的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只是在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:类型系统的问题

本文发布于:2023-05-29 23:11:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   系统   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!