@dc65k

Как правильно выполнить типизацию кода на React (children и ответ при асинхронном запросе)?

Здравствуйте. Подскажите пожалуйста, как правильно выполнить типизацию следующего кода?
Моменты, которые наиболее интересуют, это типизация children:
type TwitterProps = {
    children: any,
}


И что важно, как типизировать ответ при асинхронном запросе?
interface ITwitter {
    userId: number,
    id: number,
    title: string,
    completed: boolean,
}

const response = await fetch(url).then(response => response.json());


Ex.1
import React, {useState, useCallback, ReactFragment} from 'react';
import './App.css';

const url = 'https://jsonplaceholder.typicode.com/todos/1';

function Loading() {
    return <div>Loading</div>
}

type BadgeProps = {
    info: string
}

function Badge({info}: BadgeProps) {
    return (
        <div>
            <p>{info}</p>
            <p>Badge</p>
        </div>
    )
}

interface ITwitter {
    userId: number,
    id: number,
    title: string,
    completed: boolean,
}

type TwitterProps = {
    // children: React.ReactNode,
    children: any,
}

type TwitterState = {
    userId: string | null
}

class Twitter extends React.Component<TwitterProps, TwitterState> {

    constructor(props: TwitterProps) {
        super(props);

        this.state = {
            userId: null,
        }
    }

    /*
    state = {
        userId: null
    }

     */

    async componentDidMount() {
        const response = await fetch(url).then(response => response.json());
        console.log(response);

        const {userId} = response;

        this.setState({userId})
    }

    render() {
        console.log(this.props);

        const {children} = this.props;
        const {userId} = this.state;

        return children(userId);
    }
}

class App extends React.Component<{}, {}> {

    render() {
        return (
            <Twitter>
                {
                    (user: string) => user === null
                        ? <Loading/>
                        : <Badge info={user}/>
                }
            </Twitter>
        )
    }
}
  • Вопрос задан
  • 399 просмотров
Пригласить эксперта
Ответы на вопрос 1
Aetae
@Aetae Куратор тега TypeScript
Тлен
1. У реакта есть хэлпер PropsWithChildren<Props>. Но под капотом он просто делает так:
type PropsWithChildren<P> = P & { children?: ReactNode };

...upd: вник чутка)
Если тебе нужен render проп в children, то явно и тапизируй, никаких подвохов:
type TwitterProps = {
    children: (user: string) => ReactNode
}

2. Так и типизировать: const response: ITwitter = .... Только если какая-нить хрень прилетит то может сломаться в рантайме, так что либо ты доверяешь серверу, либо используешь какую-нить либу для дополнительной проверки вживую.)
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы