Meaning of (this as any) in TypeScript
(this as any) seems to mean the same as <any>this.
The reason why it is necessary to typecast this to any is that by doing so, the casted variable, etc. can be of any type.
The following is a concrete example.
class Aaa { private a: string = 'aiueo'; private b: string = 'aaaaa'; private c: string = 'bbbbb'; public getA(str: string) { return (this as any)[str]; } } const aaa : Aaa = new Aaa(); console.log(aaa.getA('a')); console.log(aaa.getA('b')); console.log(aaa.getA('c'));
When the above TypeScript is transpiled and executed, the result is as follows
aiueo aaaaa bbbbb
Although the string type is passed in this way, it is possible to refer to a variable by casting this as any.
To output the type of this, write as follows
console.log(this.constructor.toString());
コメント