TypeScript:类型系统问题 [英] TypeScript: problems with type system

查看:18
本文介绍了TypeScript:类型系统问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 VisualStudio 2012 中测试打字稿,但它的类型系统有问题.我的 html 站点有一个带有 IDmycanvas"的画布标签.我试图在这个画布上绘制一个矩形.这是代码

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"在类型值上不存在'HTML元素'

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 肯定存在于我的画布元素上.不过我认为这个问题很容易解决.我刚刚为画布添加了类型注释:

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:casting 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");

或使用带有 any 类型的动态查找(无类型检查):

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:类型系统问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆