如何为useState定义存储对象数组的类型?附类型报错咨询
Hey there! Let's work through your React + TypeScript state questions step by step—they're super common when getting started with typed state, so you're in good company.
1. Defining the Type for useState with an Array of Objects
First up, storing an array of Update objects is straightforward once you have your Update type defined.
First, make sure you've got either an interface or type alias for your Update structure (this is key for TypeScript to enforce type safety):
// Example interface for your Update type interface Update { id: number; content: string; timestamp: Date; // Add any other properties your Update objects use }
Then, when initializing your state, explicitly set the generic type to an array of Update (written as Update[]) and pass an empty array as the initial value:
const [messages, setMessages] = useState<Update[]>([]);
This tells TypeScript that messages will always be an array of Update objects, and it'll catch any mistakes if you try to push non-Update values into the array later.
2. Fixing the "Argument of type '{}' is not assignable..." Error
Let's break down why this error popped up:
When you wrote const [messages, setMessages] = useState<Update>({});, you did two things that clashed with TypeScript's rules:
- You told TypeScript
messagesshould be a singleUpdateobject, not an array of them (but you mentioned you originally wanted to storeArray<Updates>). - An empty object
{}doesn't match theUpdatetype—if yourUpdatehas required properties (likeidorcontentin the example above), TypeScript will throw an error because the empty object doesn't include those mandatory fields.
Here's how to fix it based on what you actually need:
If you still want to store an array of Update objects (your original goal):
Use the pattern from question 1. Then, when you want to add a single Update to the array, use the functional update form of setMessages to avoid state bugs:
// Initialize state as an empty array of Update const [messages, setMessages] = useState<Update[]>([]); // Function to add a single Update to the array const addNewUpdate = (newUpdate: Update) => { setMessages(prevMessages => [...prevMessages, newUpdate]); };
If you actually need to store a single Update object (not an array):
You have two options:
- Provide a valid initial
Updateobject that includes all required properties:const [message, setMessage] = useState<Update>({ id: 0, content: "Initial update content", timestamp: new Date() }); - Make the state optional if you don't have an initial value yet (use
Update | undefined):
Just note that when you use this state later, you'll need to handle theconst [message, setMessage] = useState<Update | undefined>(undefined);undefinedcase (e.g., using optional chaining:message?.content).
内容的提问来源于stack exchange,提问作者Mr. Robot

