2016-05-09 17 views
-1

我們如何在環境TypeScript中聲明一個函數,該函數被調用this設置爲特定類型?具有特定THIS類型的環境TypeScript函數

+0

的可能的複製[?有可能在功能方面的限制(http://stackoverflow.com/questions/21519547/is -a-constraint-on-function-context-possible) –

回答

0

您可以在功能使用this: Type作爲第一arugument:

class MyClass { 
    constructor(public myText: string) { 
    } 
} 

// enforce the context to be of type MyClass for this function 
function myFunction(this: MyClass) { 
    alert(this.myText); 
} 

var myObject = new MyClass("Hello"); 
myFunction.call(myObject);    // good 
myFunction();       // bad 
+0

我正在使用最新的TypeScript 1.8.10,並且不支持「this:MyClass」語法。我錯過了什麼? –

+0

你需要打字稿* nightlies *:https://basarat.gitbooks.io/typescript/content/docs/getting-started.html – basarat

相關問題