Qualify useState as an object in React TypeScript
To qualify a hook object in React useState
, use the hook's generics, e.g. const [employee, setEmployee] = useState<{name: string; salary: number}>({name: '',salary: 0})
the state variable will only accept key-value pairs of the specified type.
import {useEffect, useState} from 'react';
const App = () => {
// 👇️ const employee: {name: string; salary: number;}
const [employee, setEmployee] = useState<{name: string; salary: number}>({
name: '',
salary: 0,
});
useEffect(() => {
setEmployee({name: 'James', salary: 100});
}, []);
return (
<div>
<h2>Name: {employee.name}</h2>
<h2>Salary: {employee.salary}</h2>
</div>
);
};
export default App;
When initializing the hook with an object, we used generics to correctly type useState
the hook.
Sometimes we may not want to set initial values for all of an object's properties. In such cases, we can mark the property as optional.
import {useEffect, useState} from 'react';
const App = () => {
// 👇️ mark salary as optional
const [employee, setEmployee] = useState<{
name: string; salary?: number
}>({
name: '',
});
useEffect(() => {
setEmployee({name: 'James', salary: 100});
}, []);
return (
<div>
<h2>Name: {employee.name}</h2>
<h2>Salary: {employee.salary}</h2>
</div>
);
};
export default App;
We use a question mark to mark the salary attribute as optional.
This property can store an undefined value or a value of type Number.
That's why we don't need to provide it when initializing the state object.
If we provide initial values for all properties of the object, TypeScript will be able to infer the types of the state variables.
import {useEffect, useState} from 'react';
const App = () => {
// 👇️ const employee: {name: string;salary: number;}
// ✅ typed correctly without a generic
const [employee, setEmployee] = useState({
name: '',
salary: 0,
});
useEffect(() => {
setEmployee({name: 'James', salary: 100});
}, []);
return (
<div>
<h2>Name: {employee.name}</h2>
<h2>Salary: {employee.salary}</h2>
</div>
);
};
export default App;
We passed initial values for all the properties of the object, which enabled TypeScript to correctly type the employee variable.
但是
It is best to always explicitly typeuseState
your hooks, especially when working with arrays and objects.
In some cases, we may not know in advance all the properties that we want to set on an object.
import {useEffect, useState} from 'react';
const App = () => {
// 👇️ flexible object type
const [employee, setEmployee] = useState<{[key: string]: any}>({});
useEffect(() => {
setEmployee({
name: 'James',
salary: 100,
department: 'Dev',
tasks: ['dev', 'test', 'ship'],
});
}, []);
return (
<div>
<h2>Name: {employee.name}</h2>
<h2>Salary: {employee.salary}</h2>
</div>
);
};
export default App;
{[key: string]: any}
The syntax is an index signature in TypeScript, used when we don't know in advance the shapes of all the names and values of the type's properties.
The index signature in the example means that when an object is indexed with a string, it will return a
any
value of type .
This approach can be used when we don't know all the properties of an object in advance.
If you want to set an object property to one of multiple types, use a union.
import {useEffect, useState} from 'react';
const App = () => {
const [employee, setEmployee] = useState<{
name: string;
// 👇️ string OR number
salary: string | number;
}>({
name: '',
salary: '',
});
useEffect(() => {
setEmployee({name: 'James', salary: 100});
}, []);
return (
<div>
<h2>Name: {employee.name}</h2>
<h2>Salary: {employee.salary}</h2>
</div>
);
};
export default App;
We use a union to set the salary attribute to either string or number type.
If our useState
hook gets busy, extract the type passed to the generic into a type alias or interface.
import {useEffect, useState} from 'react';
type Employee = {
name: string;
salary: number;
};
const App = () => {
// 👇️ const employee: {name: string; salary: number;}
const [employee, setEmployee] = useState<Employee>({
name: '',
salary: 0,
});
useEffect(() => {
setEmployee({name: 'James', salary: 100});
}, []);
return (
<div>
<h2>Name: {employee.name}</h2>
<h2>Salary: {employee.salary}</h2>
</div>
);
};
export default App;
The syntax useState<Employee>
is easier to read, especially when dealing with large objects.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap