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

纵然是瞬间 提交于 2019-12-13 03:49:47

问题


I made an object using Typescript at Reactjs.
There is a code below.
But it makes this error in UserInformation data from password to lastname.
Could you give me some advice?

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);
  };
}

回答1:


When you know what the types of a particular object, TypeScript allows you to use interfaces like you have defined with ISignStore. Following the same pattern for UserInformation, the type would be:

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

On the other hand, the syntax you have currently used is called as an Index Signature.

interface IObject {
  [k: number]: string
}

This is basically saying that you have an object, but you don't know what keys it would have; But you are sure that the key would be a number and value would be a string. The variable k here is just a placeholder, you can use anything in that place. So, by the merit of this, there is no usage where there should be a second key for k2: number. Because k: number has already covered that case.

This is the error you are getting having defined, email, password and firstName as keys in index signature. They are just duplicate for string based key.




回答2:


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

I think you already assign type to those things.



来源:https://stackoverflow.com/questions/55321867/the-error-of-duplicate-string-index-signature-at-reactjs-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!