Typescript 是否可以对函数上下文进行约束?

Typescript 是否可以对函数上下文进行约束?,typescript,Typescript,例如,假设我有以下代码: class MyClass { constructor(public myText: string) { } } // enforce the context to be of type MyClass for this function function myFunction() { alert(this.myText); } var myObject = new MyClass("Hello"); myFunction.call(myOb

例如,假设我有以下代码:

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

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

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

在TypeScript中,是否有任何方法将
这个
变量约束为类
MyClass
的对象?这将有助于在编译时消除某些bug。

在TypeScript 2.0+中也可以这样做。使用
this:Type
注释作为函数的第一个参数:

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

如果您不能将对象引用直接传递给函数,而不是依赖于
是正确的,那么在某些情况下您可能可以使用以下稍微不同的方法:

module Test {
    export class Example {
        Test1(): void { 
           // code here
        }
    }

    export function myFunction():void {
        if (this instanceof Example) {
            var asExample: Example = <Example>this;
            asExample.Test1();
        }   
    }   
}

var ex = new Test.Example();
Test.myFunction.call(ex);
Test.myFunction();

谢谢,那太糟糕了。能够像C#的扩展方法一样定义它会很酷:
function-myFunction(this-myObject:MyClass){alert(myObject.myText);}
很好,现在支持它了<代码>--NoImplicitt这也是一个有用的补充。我不喜欢扩展方法和其他全局方法。我喜欢在github上查看文件就可以完全理解它。所有的导入都在那里,你知道任何项目都是如何运作的:)是的,我同意javascript的观点,但不是c。而且,我从来没有写过像我在这个问题上所展示的代码,哈哈。我将更多地利用
--noImplictThis
,如果它按照我认为的方式工作,我会很快指出错误。例如:将一个类重构为一个函数,让它指出所有
这个
变量,而不是像对待
任何
类型一样对待它,并且不抛出编译错误。
export function myFunction():void {
    var that = assertType<Example>(this, Example);
    that.Test1();
}   

function assertType<T>(obj:any, cls: any): T {
    if (obj instanceof cls ) {
            return <T>obj;
    }
    alert("Type mismatch");
    return null;
    //throw new Error('Type mismatch');
}