Типизация сложного JSON файла (Typescript)
На стадии осваивания Typescript и Redux столкнулся с такой проблемой. Имеем сложный JSON файл с такой сруктурой:
{
"person" :
[
{
"firstname": "",
"lastname": "",
"patronymic": "",
"age" : "",
"city" : ""
}
],
"contacts" :
[
{ "photo": "./photo.jpg",
"tel" : "",
"mail" : "mailto:",
}
],
"hobby" : ["Книги", "Музыка", "Фильмы"],
"experience" :
[
{
"id" : 1,
"year" : "",
"organization" : "",
"position" : "",
"description" : ""
}
],
"education" :
[
{
"year" : "",
"institution" : "",
"department" : "",
"specialization" : ""
}
]
}
Через Redux получаю эти данные:
import * as React from "react";
import { useSelector } from "react-redux";
interface Idatatype {
data: [];
loading: boolean;
}
const DataList: React.FC = (): JSX.Element => {
const { data, loading } = useSelector((state: Idatatype) => state);
return (
<>
{loading &&
data.map((item: any) => {
return <li>{item}</li>;
})}
);
};
export default DataList;
Подскажите, как типизировать полученные данные и вывести их
Ответы (1 шт):
Автор решения: Andrey Molodyk
→ Ссылка
Я создал тип для JSON
declare module datatype {
export interface Person {
firstname: string;
lastname: string;
patronymic: string;
age: string;
city: string;
}
export interface Contact {
photo: string;
tel: string;
mail: string;
telegram: string;
github: string;
linkedin: string;
}
export interface Position {
position: string;
employment: string;
schedule: string;
about: string;
}
export interface Experience {
id: number;
year: string;
organization: string;
position: string;
description: string;
}
export interface Education {
year: string;
institution: string;
department: string;
specialization: string;
}
export interface RootObject {
person: Person[];
contacts: Contact[];
position: Position[];
hobby: string[];
languages: string[];
hardskils: string[];
experience: Experience[];
education: Education[];
CV: [];
loading: boolean;
}
}
export { cvtype };
в коде исправил, но не уверен что верно
import * as React from "react";
import { useSelector } from "react-redux";
import { datatype } from "../../types/data";
const DataList: React.FC = (): JSX.Element => {
const { data, loading }: { data: datatype.RootObject[]; loading: boolean } =
useSelector((state: datatype.RootObject) => state);
return (
<>
{loading &&
data.map((item: any, index: number) => {
return <li key={index}>{item}</li>;
})}
</>
)
}