'How to generate types from value which is being passed in function as a param?
I have function which accepts array of objects here items prop takes an array of objets,
then the items get passed again to the Header & Content component.
Is there any way that I can generate the types based on the data which is being passed in the function.
So that I can get prop types for the the Header & Content component.
Here is the code
const data = Array.from({ length: 200 }, () => {
return {
id: faker.datatype.uuid(),
title: faker.hacker.noun(),
content: faker.hacker.phrase(),
};
});
const HeaderComp = ({ title, isOpen }: { isOpen: boolean }) => (
<div className="header">
{title} <span className={`${isOpen}`}>‚ñæ</span>
</div>
);
const ContentComp = ({ content }) => <p>{content}</p>;
const App = () => {
return (
<Accordion
items={data}
HeaderComponent={HeaderComp}
ContentComponent={ContentComp}
/>
);
};
Generated type should be
{id: string; title: string; content: string;}
Thanks in advance
Solution 1:[1]
You can get type of a variable with the typeof operator and then Pick or subscript the required fields:
type DataType = typeof data;
type DataItem = DataType[number];
type HeaderProps = Pick<DataItem, 'title'>;
type ContentProps = DataItem['content'];
Note that the resulting type depends on the TS knowledge about faker types. If faker is not typed you will get any for every field.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
