Some questions about React #783
-
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
That's a good question. |
Beta Was this translation helpful? Give feedback.
-
1.When should you use TypeScript with React instead of just JavaScript?
3.What is the difference between interface and type in TypeScript? Which one to use for props?
4.How to define a functional component with TypeScript?
6.How to style events in handlers like onClick, onChange, onSubmit...?
7.How to use TypeScript utility types like Partial, Pick, Record, Omit in React? |
Beta Was this translation helpful? Give feedback.
-
Type safety is important — it catches type errors during development, not at runtime. You work in medium/large projects where many developers contribute. You need better IntelliSense and autocompletion in editors like VS Code. The codebase must be more maintainable and self-documenting (types explain your data shape). You're integrating complex APIs or libraries where types help avoid mistakes.
tsx interface MyButtonProps { const MyButton: React.FC = ({ label, style }) => { export default MyButton;
Interface Can be extended (like inheritance). Can merge declarations (multiple interface declarations combine). Mostly used for object shapes and contracts. Type Can represent unions, intersections, primitives, tuples, and more. Cannot merge declarations. More flexible but less “extendable” in some cases. Which to use for props? If you only need an object shape → use interface (cleaner for props). If you need union types or complex compositions → use type.
tsx interface GreetingProps { const Greeting: React.FC = ({ name }) => { Hello, {name};}; export default Greeting; tsx Hello, {name};
useState tsx tsx const reducer = (state: State, action: Action): State => { const [state, dispatch] = useReducer(reducer, { count: 0 }); tsx tsx const theme = useContext(ThemeContext);
Each event in React + TypeScript has a specific type: tsx const handleChange = (e: React.ChangeEvent) => { const handleSubmit = (e: React.FormEvent) => {
Partial — makes all properties optional. tsx tsx tsx tsx tsx type OptionalButton = Partial; // All props optional |
Beta Was this translation helpful? Give feedback.
That's a good question.