Asosiy matnga o'tish
ITIT Interview
TypeScript

React bilan TypeScript

Props va children'ni tiplash, hodisalar, useState, useRef, useReducer, generic komponentlar va ComponentProps.

O'rganildi: 0 / 5
Progress

Bu nima?

React loyihalarining aksariyati TypeScript'da yoziladi. Turlar props xatolarini kompilyatsiyada ushlaydi va komponentlardan foydalanishda avtoto'ldirish beradi. React bo'limi asoslarini bilgan holda o'qing.

Props

type ButtonProps = {
  label: string;
  variant?: 'primary' | 'secondary';
  disabled?: boolean;
  onClick: () => void;
};

function Button({ label, variant = 'primary', disabled = false, onClick }: ButtonProps) {
  return <button className={variant} disabled={disabled} onClick={onClick}>{label}</button>;
}

children

import type { ReactNode } from 'react';

type CardProps = {
  title: string;
  children: ReactNode;   // JSX, matn, raqam, null, massiv — hammasi
};

function Card({ title, children }: CardProps) {
  return <section><h2>{title}</h2>{children}</section>;
}

React.FC ishlatish shart emas: oddiy funksiya va props turi yetarli va tushunarliroq.

Hodisalar

function SearchForm() {
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} />
    </form>
  );
}

Turni eslab qolish qiyin bo'lsa, handler'ni JSX ichida inline yozib, sichqonchani ustiga olib boring: editor turni ko'rsatadi.

Hooklar

const [count, setCount] = useState(0);                  // number — o'zi chiqaradi
const [user, setUser] = useState<User | null>(null);    // boshlang'ich null bo'lsa, turni ko'rsating
const [items, setItems] = useState<string[]>([]);       // bo'sh massiv — never[] bo'lmasligi uchun

const inputRef = useRef<HTMLInputElement>(null);        // DOM element uchun
inputRef.current?.focus();

const timerRef = useRef<number | undefined>(undefined); // o'zgaruvchan qiymat uchun

useReducer va discriminated union

type State = { count: number };
type Action =
  | { type: 'increment' }
  | { type: 'add'; payload: number }
  | { type: 'reset' };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'add':       return { count: state.count + action.payload };  // payload faqat shu yerda
    case 'reset':     return { count: 0 };
  }
}

const [state, dispatch] = useReducer(reducer, { count: 0 });
dispatch({ type: 'add', payload: 5 });
dispatch({ type: 'add' });   // Xato: payload yo'q

Generic komponentlar

type ListProps<T> = {
  items: T[];
  renderItem: (item: T) => ReactNode;
  getKey: (item: T) => string | number;
};

function List<T>({ items, renderItem, getKey }: ListProps<T>) {
  return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}

<List items={users} getKey={(u) => u.id} renderItem={(u) => u.name} />  // u: User

HTML elementini kengaytirish

import type { ComponentProps } from 'react';

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

function Input({ label, ...rest }: InputProps) {
  return <label>{label}<input {...rest} /></label>;
}

<Input label="Email" type="email" placeholder="..." required />

Boshqa komponentning props turini olish: ComponentProps<typeof Button>.

Intervyu savollari

Ushbu sahifada