打字稿中的索引签名如何工作?

Kar*_*rty 4 typescript angular

尝试设置对象索引签名时,出现错误的重复数字索引签名。这是工作示例,请单击此处

    export class HelloComponent implements OnInit  {
      //works
      watched: { [id: number]: boolean } = {} ; //works
      //doesnt work
      watchedOne: { [id: number]: boolean, 
        [fid: number]: boolean } = {} ; // Doesn't Work
      constructor() {}

      watch(talk): void {
        console.log('watch', talk.id);
        this.watched[talk.id] = true;
        this.watchedOne[talk.id] = true; // error
        console.log('watch-obj', this.watched); 
    }
     ngOnInit() {
        this.watch({
          id: 9,
          fid: 4
        });
     }
    }
Run Code Online (Sandbox Code Playgroud)

jca*_*alz 6

请仔细阅读The TypeScript Handbook和/或TypeScript Deep Dive中有关索引签名的部分。

也许其中没有明确为什么您需要索引签名。如果您想定义一个类型并且知道您关心的属性集(包括键名称),那么您不需要索引签名。当有人访问没有索引签名的对象并使用未知的密钥时,或者使用未知的密钥分配新的对象文字时,这是一个编译器错误:

const foo: {bar: boolean, baz: boolean} = {
  bar: true, 
  baz: false, 
  qux: false // error, extra property not expected
};
foo.bar;
foo.baz;
foo.qux; // error, no idea what qux is supposed to be
foo.quux; // error, no idea what quux is supposed to be
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,barbaz被接受,但是 上有错误qux

相反,如果您想允许任何密钥,但事先不知道它是什么,那么您可以添加索引签名:

const foo: {bar: boolean, baz: boolean, [k: string]: boolean | undefined} = {
  bar: true, 
  baz: false, 
  qux: false // no error
};
foo.bar;
foo.baz;
foo.qux; // boolean | undefined
foo.quux; // boolean | undefined
Run Code Online (Sandbox Code Playgroud)

使用单个索引签名,您可以根据需要使用正确类型的键和值设置任意数量的属性。您在签名中为索引键指定的名称根本不重要;它是任何正确类型的键的占位符。可接受的两种密钥类型是stringnumber

例如,使用单个number索引:

const foo: { [k: number]: boolean | undefined } = { };
foo[0] = true;
foo[1] = false;
foo[2] = void 0; // undefined
foo[12345] = true;
foo[54321] = false;
foo[1.5] = true;
foo[-4] = false;
Run Code Online (Sandbox Code Playgroud)

请注意,k索引签名中的 并不重要。我通常使用k,但你可以使用keyorrandom或任何东西,因为这并不重要。这只是一个占位符。


这意味着我可以通过执行以下操作来使您的上述代码正常工作:

export class HelloComponent implements OnInit  {
  name: string = "karty";
  watched: { [id: number]: boolean } = {} ;
  // single index signature
  watchedOne: { [id: number]: boolean } = {} ;
  constructor() {}

  // type annotation on talk to ensure the right types
  watch(talk: {id: number, fid: number}): void {
    console.log('watch', talk.id);
    this.watched[talk.id] = true;
    this.watchedOne[talk.fid] = true;
    console.log('watch-obj', this.watched); 
}
 ngOnInit() {
    this.watch({
      id: 9,
      fid: 4
    });
 }
}
Run Code Online (Sandbox Code Playgroud)

希望有帮助;祝你好运!