網站搜尋

javascript - 我如何在 Typescript 中從另一個檔案宣告函式?


我在一個檔案中有以下函數:

function alertWin(title, message) {
   .......
   .......
}

在另一個 TypeScript 檔案中,我有:

function mvcOnFailure(message) {
    "use strict";
    alertWin("Internal Application Error", message);
}

我收到一個錯誤,說「alertwin」在當前範圍中不存在。

解決這個問題的方法是我在另一個檔案中定義這個函數然後再引用它嗎?如果是的話,那麼這個定義會長什麼樣子?

答案#1

你可以這樣做(假設標題和訊息都應該是字串):

interface alertWinInterface{
    (title:string, message: string):any;
}

declare var alertWin: alertWinInterface;

你可以把這個放在同一個檔案中,或者放在一個單獨的環境定義檔案 (.d.ts) 並進行匯入:

/// <reference path="myDefinitions.d.ts" />

或者,你也可以直接導入包含實際函數定義的另一個檔案,但你將無法獲得靜態類型支持。

答案#2

這種方法似乎對我有效:

declare function alertWin(title: string, message: string) : void;

就像馬特的解決方案一樣,你把它放在一個定義文件中,然後再引用它。