Capítulo 9 de 116
TypeScript adds type safety to React components and Hooks primarily through inference — most component and Hook code needs little to no extra type annotation beyond installing @types/react and @types/react-dom and typing what can't be inferred (props, refs, complex event handlers).
@types/react and @types/react-dom added as dev dependencies alongside typescript itself.function Avatar({ person, size }: { person: Person; size: number }) — no special "FC" wrapper type is recommended; a plain typed function is preferred.useState<T>(): usually inferred from the initial value; an explicit type argument is needed mainly when the initial value doesn't fully describe the type (e.g. useState<Status | null>(null)).useReducer: benefits from explicitly typing the action union so the reducer's switch is exhaustively checked.useContext: typed by the type parameter given to createContext<T>().useRef: typing depends on whether the ref is DOM-attached (useRef<HTMLInputElement>(null)) or holds a mutable value.React.ReactNode (anything renderable, including children), React.CSSProperties (the style prop's object shape), React.ComponentProps<typeof SomeComponent> (extract another component's prop types instead of redeclaring them), and DOM event types like React.MouseEvent<HTMLButtonElement> for handler parameters.type-challenges) to actually learn the language; this chapter is about the React-specific typing surface only.function Avatar({ person, size }: { person: Person; size: number }) {
return <img className="avatar" src={getImageUrl(person)} width={size} height={size} />;
}
React.FC wrapper.useState(0) infers number) and only add explicit generics where the initial value under-specifies the type (nullable state, union types).React.ComponentProps<typeof Component> avoids duplicating another component's prop shape when writing a thin wrapper around it.useState calls this chapter shows how to type.