简体   繁体   中英

How to set an an object with a dynamic key as React state in Typescript

I am using React and Typescript and need to create an object with a dynamic key that has two pre-defined properties. The field is dynamic so I can't pre-define it in Typescript. The structure I have attempted to implement in the interface is:

[field: string]: {
   property1: string,
   property2: string
}

I then want to be able to dynamically set the key of this object. Such as,

let item: string = "randomTest"

 this.setState({
    [item].property1: "test value 1"
 })

And access it through:

this.state[item].property1

However, when I attempt to implement this structure in the Typescript interface, the state keys that are not in the dynamic object throw an error saying they are "not assignable to string index type '{property1: string}'. For example, testKey1 below would throw this error:

[field: string]: {
   property1: string,
   property2: string
};
testKey1: string;

This error seems to be saying that testKey1 is in the [field] object even though it isn't.

How can I effectively define an object with a dynamic key as React state in Typescript?

在 testKey1 之前添加一个 semecon: string;

You can use the Record built-in type added in TypeScript 2.1. Record

interface MyObject {
  property1: string;
  property2: string;
}

type DynamicObject = Record<string, MyObject>;

Replace

[field: string]: {
   property1: string,
   property2: string
}

by

    interface Anything {
      [key: string]: any;
    }

And when you're calling then: do this

let item = { property1: "randomTest", property2: "randomTest1", property3: "randomTest3"}

 this.setState({
    [item].property1: "test value 1"
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM