Nicolas S.Xu Nicolas S.Xu - 2 months ago 7
TypeScript Question

In Typescript what is array as function name?

The below code is correctly compiled and executed by ts-node.

class C {
["abc"]() {
return "C";
}
}

let c = new C();

let className = c["abc"]();
console.log(className);


But I don't understand the following as class property.

["abc"]() {}


I think it involves a concept of computed property, but I don't understand this syntax.

Question 1:

["abc"] is an array with one string element at index 0. If you add a function definition around it, then ["abc"](){}, then what is it then? How could you use an array as function name?

Question 2:

why not the following way to invoke the member method?

c.["abc"]();

Answer

Just like foo['bar'] and foo.bar are equivalent ways to access an object member, you can use the indexer syntax with ['bar'] within object initializers and class definitions.

For your example, where the property is statically known at compile-time, this does not really offer you any advantage, since it’s directly equivalent to the following:

class C {
    abc() {
        return "C";
    }
}

However, the indexer syntax does allow you a few things that otherwise wouldn’t be possible.

For example, you can use member names that are not valid identifiers, e.g. names that start with a number, or have a dash inside:

class C {
    ['123foo']() { … }
    ['foo-bar']() { … }
}

It also allows you to dynamically specify the member name, by taking it from a variable:

let memberName = 'foo';
class C {
    [memberName]() { return 'bar'; }
}
console.log(new C().foo()); // bar

This is also used for Symbols in JavaScript, which offer a way to define members on objects that are not freely visible but only accessible with a direct access to that same symbol object. This will ultimately allow new high-level functionality, like Symbol.iterator does for iterating custom types.