Tech Interview RoomStudy guides

TypeScript

How do you type React components, hooks and events in TypeScript?

Intermediate · 2 min read · Lesson 6 of 7 in TypeScript

Props

  • Type props with a type or interface and destructure them: function Card({ title }: CardProps).
  • children: React.ReactNode for anything renderable.
  • Avoid React.FC; plain functions are simpler and support generics.
  • Extend native element props with React.ComponentProps<'input'> so ...rest can be forwarded. In React 19, ref is a normal prop, so no forwardRef is needed.

Hooks

  • useState infers from the initial value; give a type when it starts empty: useState<User | null>(null).
  • useRef<HTMLInputElement>(null) for DOM refs.
  • useReducer infers from the reducer; type actions as a discriminated union.
  • Custom hooks returning tuples need as const to keep tuple types.

Events

React.ChangeEvent<HTMLInputElement>, React.FormEvent<HTMLFormElement>, React.MouseEvent<HTMLButtonElement>. Inline handlers get these types inferred for free.

Example

tsx
type InputProps = React.ComponentProps<'input'> & { label: string };

function TextInput({ label, id, ...rest }: InputProps) {
  return (
    <label htmlFor={id}>
      {label}
      <input id={id} {...rest} />
    </label>
  );
}

function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = useCallback(() => setOn(v => !v), []);
  return [on, toggle] as const;          // readonly [boolean, () => void]
}

function Search() {
  const [query, setQuery] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setQuery(e.target.value);
  return <TextInput label="Search" id="q" ref={inputRef} value={query} onChange={onChange} />;
}

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you type a Vue component's props and emits?

With <script setup lang="ts">: const props = defineProps<{ title: string; count?: number }>() and const emit = defineEmits<{ change: [value: number] }>(). Defaults come from destructuring in Vue 3.5 (const { count = 0 } = defineProps<...>()) or withDefaults. vue-tsc type-checks templates as well.