basarat/typescript-book

Wrong: All members must conform to the string index signature?

Schokokex opened this issue · 1 comments

origin

i copied the Foo and Bar into ts playground and it works.

interface Foo {x:number; y:string}
const index: 'x'|'y' = fromSomewhere;
const foo1: Foo = { x:1, y:"a b c"}
const bar: string | number = foo1[index];

I also tried the examples and they did work for me too.

I think what the author actually meant is that when such an interface is defined:

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

any members which have a string type key must have a number type value. In this case, trying to create an object member with a string type value would throw an error:

const foo: Foo = {
  x: 1, // Okay
  y: 'abc' // Error
};

If this is the case, this tutorial section examples are misleading.