React.js+TypeScript状态理解及TS只读类型报错解决方案咨询
Hey there! Let’s work through this TypeScript error you’re facing. That message typically crops up when you’re trying to access a Persons property on a value TypeScript has flagged as readonly, or the type definition for that value doesn’t include the Persons property at all. Here are the most reliable fixes to try:
1. Verify Your Type Definitions
First, check the type/interface for the value you’re accessing. This is the most common culprit—if your type doesn’t explicitly include Persons, TypeScript will throw this error.
For example, if you’re using a state object or API response:
// ❌ Wrong: Missing Persons in the type definition interface AppState { // No Persons property here } // ✅ Correct: Explicitly define the Persons property interface Person { id: number; name: string; } interface AppState { Persons: Person[]; }
Even if the value is marked as readonly (like Redux state), you can still access its properties as long as the type includes them.
2. Check Your Data Structure
Sometimes you might be working with a readonly array instead of an object that contains the Persons array. For example:
// ❌ Error: Trying to access Persons on a readonly array const readonlyPersonArray: readonly Person[] = fetchPersons(); const myPersons = readonlyPersonArray.Persons; // This won't work
Fix this by ensuring your data is structured as an object with the Persons property:
// ✅ Correct structure interface ApiResponse { Persons: Person[]; } const response: ApiResponse = await fetch("/api/persons"); const myPersons = response.Persons;
3. Correct React State Typing
If you’re using React’s useState, make sure you explicitly type your state to include Persons, especially if the initial value might lead TypeScript to infer a readonly type:
// ❌ Risky: Type inference might miss Persons const [state, setState] = useState(readonly []); // ✅ Safe: Explicitly define the state type const [state, setState] = useState<{ Persons: Person[] }>({ Persons: [] });
4. Type Assertion (Last Resort)
If you’re certain the value has a Persons property but TypeScript isn’t picking it up, you can use a type assertion. Note: Only use this when you’re 100% sure about the data structure—it can hide real type issues.
const rawData = getSomeData(); const dataWithPersons = rawData as { Persons: Person[] }; const myPersons = dataWithPersons.Persons;
Start with checking your type definitions first—that’s almost always where the problem starts. Double-check your data structure to avoid mixing up arrays and objects, and you should be good to go!
内容的提问来源于stack exchange,提问作者Great Khan 2016

