Reactjs with Typescript 的 'Duplicate string index signature' 错误

The error of 'Duplicate string index signature' at Reactjs with Typescript

我在 Reactjs 上使用 Typescript 制作了一个对象。
下面有代码。
但是它在从密码到姓氏的用户信息数据中产生了这个错误。
你能给我一些建议吗?

Duplicate string index signature

import { observable, action } from 'mobx';

export interface ISignStore {
  email: string,
  password: string,
  firstName: string,
  lastName: string,
  handleInput(e: any): void,
  handleSubmit(e: any): void
}

export class SignStore implements ISignStore {
  @observable
  UserInformation: {
    [email: string]: '',
    [password: string]: '',
    [firstName: string]: '',
    [lastName: string]: ''
  };

  @action
  handleInput = (e: any): void => {
    [e.target.id] = e.target.value;
  };

  @action
  handleSubmit = (e: any): void => {
    e.preventDefault();
    console.log(this.UserInformation);
  };
}
 UserInformation: {
    [email]: '',
    [password]: '',
    [firstName]: '',
    [lastName]: ''
  };

我想你已经为那些东西指定了类型。

当您知道特定对象的类型时,TypeScript 允许您使用您用 ISignStore 定义的接口。按照 UserInformation 的相同模式,类型将是:

interface IUserInformation {
  email: string;
  password: string;
  firstName: string;
  lastName: string;
}

另一方面,您当前使用的语法称为 Index Signature

interface IObject {
  [k: number]: string
}

这基本上是说你有一个对象,但你不知道它会有什么键;但是您确定键是数字,值是字符串。这里的变量 k 只是一个占位符,你可以在那个地方使用任何东西。因此,由于这个优点,没有使用 k2: number 应该有第二个键的地方。因为 k: number 已经涵盖了那个案例。

这是您将 emailpasswordfirstName 定义为索引签名中的键时遇到的错误。对于基于 string 的密钥,它们只是重复的。