ts 與 js 的呼叫

weixin_34097242發表於2017-07-11

源自網路:

ts 是 js 的超集,因此只要是 js 與 js 可以互相呼叫的,ts 均可以呼叫,只不過需要增加宣告來解決編譯時報錯。

ts 最終生成的檔案為 js,因此 js 呼叫 ts 其實就是 js 呼叫 js(ts 生成的 js 檔案)。

ts 呼叫 js

步驟

找到 js 呼叫 js 的方法。

增加方法呼叫的宣告。 請參考如何生成 .d.ts

示例

js 內的方法

functioncallJsFunc(msg){

console.log("msg from egret : "+msg);

}

ts 內宣告

declare functioncall JsFunc(msg:string);//可以放在 ts 檔案內(建議在頂部或者底部,中間的沒試過)或者單獨放到一個 .d.ts 檔案中,請不要放在其他型別的檔案內。msg 型別根據函式體判斷。

ts 內呼叫

callJsFunc("hello js");

輸出

msg frome gret:hello js

總結:在 js 呼叫 js 的基礎上增加宣告。其他的比如變數等,也是按上面步驟來實現。

js 呼叫 ts

js 呼叫 ts 其實就是 ts 呼叫 ts,由於 ts 呼叫 ts 可能會有同模組下的省略寫法,因此只要使用不同模組下的呼叫來寫即可。

步驟

找到非同一模組下 ts 的呼叫(比如example.A.CallEgretFunc("hello"))。

完全按上面呼叫的方式來寫 (比如上面的example.A.CallEgretFunc("hello"))。

示例

ts 內的方法

moduleexampleA{

exportclassA{

publiccallEgretMethod(msg:string):void{

console.log("method msg from js : "+msg);

}

publicstaticCallEgretFunc(msg:string):void{

console.log("static msg from js : "+msg);

}

}

}

非同一模組下 ts 呼叫

moduleexampleB{

exportfunctionb(){

//呼叫方法

vara:exampleA.A=newexampleA.A();

a.callEgretMethod("method");

//呼叫靜態函式

exampleA.A.CallEgretFunc("function");

}

}

js 內呼叫

vara=newexampleA.A();//去掉 a 的型別

a.callEgretMethod("method");

exampleA.A.CallEgretFunc("function");

輸出

method msgfromjs:method

staticmsgfromjs:function

總結:相當於非同一個模組下的 ts 呼叫 ts。其他的比如變數等,也是按上面步驟來實現。

相關文章