Odatda biz nima yo’l tutamiz
Odatda react komponent yasashda quiyida keltirilgan yo’ldan foydalaniladi va har safar items props dan kelayotgan malumotni type ni qo’lda o’zgartirishga to’g’ri keladi. Quyidagi kodni 17 chi qatorida hatolik beradi, sababi items type ni ichida name degan field yo’q.
import React from "react";
interface TableProps { items: { id: string }[]; renderItem: (item: { id: string }) => React.ReactNode;}
export const Table = (props: TableProps) => { return null;};
export const Component = () => { return ( <Table items={[{ id: "1", name: "Alex" }]} renderItem={(item) => { item.name; // typescript hatolik beradi return null; }} ></Table> );};
Keling buni to’g’irlaymiz
Quyida keltirilgan o’zgarishlar orqali Table komponentimizmi dinamik tip oladigan qilib o’zgartiramiz. Yani items ni tipini items props dan keladigan malumotni tipiga qarab oladi.
import React from "react";
interface TableProps { items: { id: string }[]; renderItem: (item: { id: string }) => React.ReactNode;}interface TableProps<T> { items: T[]; renderItem: (item: T) => React.ReactNode;}
export const Table = (props: TableProps) => {export const Table = <T,>(props: TableProps<T>) => { return null;};
export const Component = () => { return ( <Table items={[{ id: "1", name: "Alex" }]} renderItem={(item) => { item.name; // bu holatda typescript hatolik bermaydi return null; }} ></Table> );};
Savolingiz yoki biror bir fikringiz bo’lsa izohda yozib qoldiring.