React函数组件中定义State的最佳实践:两种写法对比
Great question! Let’s unpack these two TypeScript approaches for typing your React component’s state and clarify why one is far better suited for most cases.
First Approach: Explicit Array Type Annotation
export function TestComponent() { const [state, setState]: [string, Function] = React.useState(''); }
While this technically works, it has a critical downside: the Function type for setState is way too vague. React’s setState isn’t just any function—it’s a specific utility that accepts either the new state value or a callback function that takes the previous state and returns the updated state. By using Function, you lose all TypeScript type checking for setState’s arguments. For example, you could accidentally pass a number to setState and TypeScript wouldn’t flag it, even though that would cause unexpected behavior in your component.
Second Approach: Generic Type Argument
export function TestComponent() { const [state, setState] = React.useState<string>(''); }
This is the optimal choice—and your instinct to prefer it because it’s cleaner is totally correct! Here’s why it’s the better option:
- Precise, automatic typing for setState: When you use the generic
useState<string>, TypeScript automatically infers the exact type forsetState(it’ll be(value: string | ((prevState: string) => string)) => void). This means you get full type safety: if you try to pass a non-string value tosetState, TypeScript will throw an error immediately, catching bugs early in your workflow. - Conciseness: You don’t have to manually type out the entire array structure—React’s built-in useState generic handles all that heavy lifting for you.
- Flexibility for complex state: This syntax really shines when working with more complex state types (like unions, custom interfaces, or nullable values). For example, if your state could be a string or null, you’d write
useState<string | null>(null)—far cleaner than writing out the full array type with all possible state and setState argument variations.
Final Verdict
Stick with the generic useState<string>('') syntax. It’s not just more concise—it provides better type safety and aligns with React and TypeScript’s recommended best practices.
内容的提问来源于stack exchange,提问作者D.Bronder

