2012-10-02 31 views
2

我想引用使用Resig的「擴展」已有的代碼,但我得到了一堆錯誤打字稿:引用Resig的延長

的------ ----- test.ts ---

/// <reference path="myclass.js" /> 
var m = new MyClass (3); 

------ myclass.js --------

/// <reference path="class.js" /> 

var MyClass = Class.extend({ 

    init: function (i) 
    { 
     this.i = i; 
    }, 
}) 

------ class.js ------- -

(copied from http://ejohn.org/blog/simple-javascript-inheritance/) 

錯誤:

Supplied parameters do not match any signature of call target 
The name 'Class' does not exist in the current scope 
The property 'extend' does not exist on value of type '() => void' 
The name 'Class' does not exist in the current scope 

我知道最終我會想重寫擴展爲基礎的代碼打字稿,但在那之前,我要如何新代碼中引用呢?

我想這引發了更深的問題 - 爲什麼它抱怨現有的JavaScript代碼中的類型錯誤?

回答

3

TypeScript通常不能從外部JavaScript代碼推斷出類型。

你需要聲明你打電話到使打字稿知道什麼類型的形狀是「擴展」代碼的形狀:

declare class Class { 
    static extend(body: any); 
} 

您可以把在源文件直接(如果你只有一個單一文件項目),或者更正確地說,在你從源文件引用的'.d.ts'文件中。

+0

我很困惑。如果我在我的.ts文件中添加標記,我會在Visual Studio的'錯誤列表'窗口中看到錯誤,所以它至少試圖解析它。你是說TypeScript不能推斷出那些類型,但會爲它們產生錯誤嗎?我想我不確定互操作的故事在這裏。如果我必須編寫.d.ts文件,爲什麼它會打擾解析.js文件? – Spongman

+0

仍然可以看到類似於函數和變量的推斷類型,所以引用.js的用例不需要編寫.d.ts文件。 –

+0

沒錯,但是我的觀點是IMO從錯誤中推斷錯誤是沒有用的一些你沒有完全推斷出來的東西,目前的行爲意味着通常不可能引用現有的代碼。 – Spongman