Reactjs与Typescript的“重复字符串索引签名”错误

问题描述 投票:0回答:2

我在Reactjs使用Typescript创建了一个对象。 下面有一个代码。 但是它会在UserInformation数据中将此错误从密码更改为姓氏。 你能给我一些建议吗?

重复的字符串索引签名

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);
  };
}
reactjs typescript mobx
2个回答
1
投票

当您知道特定对象的类型时,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键的重复。


0
投票
 UserInformation: {
    [email]: '',
    [password]: '',
    [firstName]: '',
    [lastName]: ''
  };

我想你已经为那些东西分配了类型。

© www.soinside.com 2019 - 2024. All rights reserved.