Search code examples
typescriptfabricjstypescript-typings

What means [key in string] used to write an array's entries signatures?


I was reading about interfaces with index signatures which allows to write an interface like this for an array:

interface StringArray {
  [index: number]: string;
}

And also i saw this example from this thread which allows writting signature in this way too:

type ResponseKeys = 'devices' | 'languages' | 'frameworks' | 'backend';

export class Survey {
  isCompleted: boolean;
     response: {
       [key in ResponseKeys]: string[]
     };
 }

but what means [key in string] i found somewhere in a doc :

const [texts, setTexts] = useState<{ [key in string]: fabric.ITextboxOptions }>({
  '0': { text: 'A', left: 0 },
  '1': { text: 'B', left: 30 },
  '2': { text: 'C', left: 60 },
});

even when i tried to read about the 'in operator' i couldn't find a meaning to test if a key is in a string type. Any clue please ?


Solution

  • Edit this

    interface Invalid {
      [key in string]: string;
    }
    
    interface Valid {
      [key: string]: string;
    }
    
    type ValidType = {
      [key in string]: string;
    }
    

    Playground

    type is more flexible and will accept both syntaxes. Also [key in type] is more flexible and will allow some uses that in does not, but I don't have them at hand.

    As of why do they exist? I don't know...


    Original answer:

    The { [key in string]: T } is kind of a wildcard. It means the object assigned must have only string keys.

    • 'property' is ok
    • '0' is ok
    • 0 is not
    const obj: { [key in string]: number } = {};
    
    obj['0'] = 1; // ok
    obj[0] = 1; // not ok!
    obj.property = 1; // ok