A
A
Alexey2021-09-08 12:34:28
typescript
Alexey, 2021-09-08 12:34:28

How to define a type in TypeScript?

There is a difficulty in understanding types in TypeScript. It means not simple types "number, string, ...".

For example code from next.js:

class MyDocumnet extends Document {

    static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
        const initialProps = await Document.getInitialProps(ctx);
        return {...initialProps};
    }

    render(): JSX.Element {
        return (
            <Html lang="ru">
                <Head />
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}


1) How to determine that the getInitialProps function returns a Promise and even DocumentInitialProps?

or here's another example

2) How to determine that the render function returns JSX.Element?

In JS, it is possible to determine the type by typeof, how to be in Typescript? I don't understand the fundamental basis, the return type definition.

I really want to understand this issue, I'm tired of guessing, I want understanding.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2021-09-08
@AleksRap

You specify the return type yourself. That is, you must know what is returned and write ts about it
by promise - functions with async return a promise by default, plus you must specify what will be returned after the promise is fulfilled. It might even be unknow if you don't know the type
from JSX.Element - the render function returns JSX.Element. Therefore, this type is indicated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question