Difference between `[key: string]` and `[key in string]` in TypeScript index signatures

458 Views Asked by At

Consider there following examples that use :and in to define index signatures:

interface Colon {
  [key : string]: number;
}

interface ColonOpt {
  [key : string]?: number; // does not compile
}

interface In {
  [key in string]: number; // does not compile
}

interface InNested {
  a: {
    [key in string]: number;
  };
}

interface InNestedOpt {
  a: {
    [key in string]?: number;
  };
}

I am a bit confused why some compile and some don't. What's the difference of using in vs : in index signatures?

0

There are 0 best solutions below