2012-12-02 22 views
53

Właśnie testuję maszynopis w Visual Studio 2012 i mam problem z jego typem systemu. Moja strona html ma tag canvas z identyfikatorem "mycanvas". Próbuję narysować prostokąt na tym płótnie. Oto kodTypeScript: problemy z systemem typu

var canvas = document.getElementById("mycanvas"); 
var ctx: CanvasRenderingContext2D = canvas.getContext("2d"); 
ctx.fillStyle = "#00FF00"; 
ctx.fillRect(0, 0, 100, 100); 

Niestety VisualStudio zarzuca

the property 'getContext' does no exist on value of type 'HTMLElement'

To oznacza drugą linię jako błąd. Myślałem, że to będzie tylko ostrzeżenie, ale kod się nie skomplikuje. VisualStudio mówi, że w ogóle nie podobał mi się ten błąd. Dlaczego nie ma wywołania metody dynamicznej? Po wszystkim metoda getContext zdecydowanie istnieje w moim elemencie canvas. Jednak myślałem, że ten problem będzie łatwy do rozwiązania. Właśnie dodałem adnotację typu do płótna:

var canvas : HTMLCanvasElement = document.getElementById("mycanvas"); 
var ctx: CanvasRenderingContext2D = canvas.getContext("2d"); 
ctx.fillStyle = "#00FF00"; 
ctx.fillRect(0, 0, 100, 100); 

Ale system typów wciąż nie był spełniony. Oto nowy komunikat, tym razem w pierwszej linii:

Cannot convert 'HTMLElement' to 'HTMLCanvasElement': Type 'HTMLElement' is missing property 'toDataURL' from type 'HTMLCanvasElement'

Cóż, jestem na całość do typowania statycznego, ale to sprawia, że ​​język bezużyteczny. Czego chce ode mnie system typów?

UPDATE:

Typescript ma faktycznie żadnego wsparcia dla dynamicznego inwokacji i mój problem może być rozwiązany z typecasts. Moje pytanie jest w zasadzie kopią tej jednej TypeScript: casting HTMLElement

Odpowiedz

116
var canvas = <HTMLCanvasElement> document.getElementById("mycanvas"); 
var ctx = canvas.getContext("2d"); 

lub stosując dynamiczną odnośnika z typem any (bez typechecking):

var canvas : any = document.getElementById("mycanvas"); 
var ctx = canvas.getContext("2d"); 

Można spojrzeć na różne rodzaje w lib.d.ts.

+4

Warto wspomnieć, że lepiej jest użyć 'CanvasRenderingContext2D' zamiast' any' type dla kontekstu canvas. –

+1

Od TypeScript 1.8 rozpozna ciągły ciąg znaków "2d" ', a' .getContext ("2d") 'zwróci z typem' CanvasRenderingContext2D'. Nie musisz go rzucać jawnie. –

1

Miałem ten sam problem, ale z SVGSVGElement zamiast HTMLCanvasElement. Casting do SVGSVGElement dał błąd kompilacji:

var mySvg = <SVGSVGElement>document.getElementById('mySvg'); 

nie można przekonwertować 'HTMLElement' do 'SVGSVGElement':
typu '' HTMLElement brakuje własność 'width' od typu 'SVGSVGElement'.
W typie "SVGSVGElement" brakuje właściwości "onmouseleave" z typu "HTMLElement".

Jeżeli poprawiony przez pierwszego castingu do 'każdego':

var mySvg = <SVGSVGElement><any>document.getElementById('mySvg'); 

lub w ten sposób (ma identyczny efekt)

var mySvg: SVGSVGElement = <any>document.getElementById('mySvg'); 

Teraz mySvg jest silnie wpisany jako SVGSVGElement.

Powiązane problemy