Why square brackets in the type declaration of an object key?
Why square brackets in the type declaration of an object key?
I need this:
Impact: = 0: "Minor", 1: "Major", 2: "Critical" ;
If I want to annotate the type explicitly, it is:
Impact: [key: number]: string = 0: "Minor", 1: "Major", 2: "Critical" ;
Why not:
Impact: number: string = 0: "Minor", 1: "Major", 2: "Critical" ;
What do the square brackets mean? Is key a reserved word?
key
Possible duplicate of Square Brackets Javascript Object Key
– Li357
Aug 20 at 3:09
1 Answer
1
The square brackets are mnemonic for the square brackets that you would use to access an element:
let Impact: [key: number]: string = ...;
console.log(Impact[0]);
Compare to a call signature, which can be declared like this:
let Impact: (key: number): string = ...;
// equivalent shorthand:
// let Impact: (key: number) => string;
console.log(Impact(5));
The name key is an arbitrary parameter name in both cases.
key
The number: string syntax is already used for an object with a single property named number.
number: string
number
Thanks. So the square brackets have nothing to do with arrays?
– Old Geezer
yesterday
I wouldn't say that. They aren't being used in this case to actually index an array, but they symbolize the square brackets that would be used to index an array; that's why the same symbol was chosen.
– Matt McCutchen
yesterday
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It's a computed property name, from ES2015.
– Li357
Aug 20 at 3:08