Reputation: 6137
I was going through the new features of TypeScript 2.9 and came across this part of code:
const c = "c";
const d = 10;
const e = Symbol();
const enum E1 { A, B, C }
const enum E2 { A = "A", B = "B", C = "C" }
type Foo = {
a: string; // String-like name
5: string; // Number-like name
[c]: string; // String-like name
[d]: string; // Number-like name
[e]: string; // Symbol-like name
[E1.A]: string; // Number-like name
[E2.A]: string; // String-like name
}
type K1 = keyof Foo; // "a" | 5 | "c" | 10 | typeof e | E1.A | E2.A
What does [c]: string;
inside type Foo
mean and what is its purpose?
Upvotes: 0
Views: 162
Reputation: 251022
Computed property names allow you to use another variable to specify the name of a property.
Here is a shorter example:
const c = 'test';
const example = {
[c]: 'test value'
};
// Note: this is for illustration - it works and shows what has happened
console.log(example.test);
// This is more likely how you would refer to the property
console.log(example[c]);
This particular example works as if test
had been specified as the property name:
const example = {
test: 'test value'
};
console.log(example.test);
You could use it, for example, to dynamically name a property on an object - referring to it by the variable that contains the name. TypeScript will track that variable in order to provide type information for the dynamic property, i.e. example.[c] is a string
Upvotes: 2