Search code examples
typescript

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?


Solution

  • 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.

    The {number: string} syntax is already used for an object with a single property named number.