简体   繁体   中英

Type for object in React/Typescript

What is the type for a object in React/Typescript for example:

const [value, setValue] = React.useState<any>({});

if I need to define it as an object what type would I put in, instead of <any>

interface MyObject {
  [k: string]: any;
}

const [value, setValue] = React.useState<MyObject>({});

[k: string]: any; means that property must be a string, and it's value are any.

You would use your own type, for example. Refer to other SO threads like this one: Set types on useState React Hook with TypeScript

If you have a generic object and you only need to define it is some object with properties and values, you can simply define it like this const [value, setValue] = React.useState<{[key: string] : any}>({});

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