使用Typescript在Reactjs中出现'重复的字符串索引签名'的错误 [英] The error of 'Duplicate string index signature' at Reactjs with Typescript

查看:556
本文介绍了使用Typescript在Reactjs中出现'重复的字符串索引签名'的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

当您知道特定对象的类型时,TypeScript允许您使用与ISignStore定义的接口.遵循UserInformation的相同模式,类型为:

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
}

这基本上是说您有一个对象,但是您不知道它将拥有什么键;但是您确定键将是一个数字,而值将是一个字符串.这里的变量k只是一个占位符,您可以在该位置使用任何东西.因此,凭此优点,在k2: number应该有第二个键的地方没有用处.因为k: number已经涵盖了这种情况.

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.

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

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.

这篇关于使用Typescript在Reactjs中出现'重复的字符串索引签名'的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆