Search code examples
typescriptnativescriptnativescript-plugin

why declare method within square brackets wrapped around name in typescript?


I've been going through nativescript code base to see how to update some of my plugins for {N} 3.0.1, and i see a lot of class methods this way.

[srcProperty.setNative](value: any) {
    this._createImageSourceFromSrc(value);
}

see the contents of image-common.ts and image.android.ts to see the full source.

why are the properties of the exported const from image-common.ts used in image.android.ts a methods, and why are they wrapped in square brackets ?


Solution

  • It generates a property with the computed name on that class's prototype.

    While not very used this perfectly valid javascript/typescript code. It does result in some loss of typing though.

    This typescript code:

    let propName = 'someMethod';
    
    class A {
      [propName](): number {
        console.log(propName);
        return 5;
      }
    }
    
    let a = new A();
    
    let x = a[propName]()
    

    Will result in this javascript output.

    var propName = 'someMethod';
    var A = (function () {
        function A() {
        }
        A.prototype[propName] = function () {
            console.log(propName);
            return 5;
        };
        return A;
    }());
    var a = new A();
    var x = a[propName]();
    

    You can see a working example here.