How can I disable "this" keyword in TypeScript?

时间:2018-02-03 10:29:02

标签: typescript visual-studio-code typescript2.0

is there a way to disable the necessarity for the this keyword in classes? Simple example below:

class counter {
    public runCounter() {
        console.log("testconsole");
        vartest = 123; // Gives error :(
    }
    public vartest: string;
}

let cter = new counter();

cter.runCounter();

This gives error: [ts] Cannot find name 'vartest'. Did you mean the instance member 'this.vartest'?

Is there a way to get implicit access to the member if there is no other variable with the same name? This works fine in other languages like C#.

1 个答案:

答案 0 :(得分:1)

No, not really. Sorry.

You could instead do something like:

class counter {
    public runCounter() {
        let _ = this;
        console.log("testconsole");
        _.vartest = 123; // Gives error :(
    }
    public vartest: string;
}

but it makes it much more obscure rather than easier - and I doubt it's any nearer what you were looking for in any event.

I think the best advice would be to just get used to rolling with the common conventions and best practices of TypeScript when writing TypeScript rather than trying to shoehorn what you've been used to from other languages.

I know it can be a bit awkward to shed those deeply ingrained habits but the rewards (easier to read code, working with the language rather than against it, etc.) will be well worth your endeavours