什么是 [key in string] 用来写数组的条目签名?

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

我正在阅读有关 interfaces with index signatures 的内容,它允许为数组编写这样的接口:

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

我还从 看到了这个例子,它也允许以这种方式写签名:

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

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

但是我发现 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 },
});

即使我试图阅读有关“in operator”的内容,我也找不到测试键是否为字符串类型的含义。 请问有什么线索吗?

编辑这个

interface Invalid {
  [key in string]: string;
}

interface Valid {
  [key: string]: string;
}

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

Playground

type 更灵活,可以接受两种语法。 [key in type] 也更灵活,允许一些 in 不允许的用途,但我手边没有。

至于它们为什么存在?我不知道...


原回答:

{ [key in string]: T } 是一种通配符。这意味着分配的对象必须只有字符串键。

  • 'property' 可以
  • '0' 可以
  • 0 不是
const obj: { [key in string]: number } = {};

obj['0'] = 1; // ok
obj[0] = 1; // not ok!
obj.property = 1; // ok