0

New to Typescript.

I'm trying to create an object from an API call, I only want to pass to this new objects some data. This objects will store a list of objects that will contain an id, a name and content.

I've created a type:

type JokesData = {
    jokes: {
        id: string;
        name: string;
        content: string;
    };
};

This is my function to get the data and generate object:

export const getJokes = async () => {
    const res = await fetch("http://localhost:3000/api/jokes");
    const data = await res.json();

    const jokesList: JokesData = {
        jokes: data.docs.map(({ id, name, content }) => ({
            id,
            name,
            content,
        })),
    };

    return jokesList;
};

My question is how can I pass the id, name, and content type when I map the object? enter image description here

Please, any help on this will be very appreciated! Cheers!

Added a new type an I nested it the JokesData type

// types
type JokesData = {
    jokes: JokesDataItems[];
};

type JokesDataItems = {
    id: string;
    name: string;
    content: string;
};

the function that maps the object

export const getJokes = async () => {
    const res = await fetch("http://localhost:3000/api/jokes");
    const data = await res.json();

    const jokesList: JokesData = {
        jokes: data.docs.map(({ id, name, content }: JokesDataItems) => ({
            id,
            name,
            content,
        })),
    };

    return jokesList;
};

It still doesn't work, when using this jokeList in a component the types aren't passed properly.

Update Answer thanks to Nuridin

This works:

type JokesData = {
    docs: JokesDataItems[];
};

type JokesDataItems = {
    id: string;
    name: string;
    content: string;
};

// get a list of jokes
export const getJokes = async () => {
    const res = await fetch("http://localhost:3000/api/jokes");
    const data: JokesData = await res.json();

    return {
        jokes: data.docs
            .splice(0, 5)
            .map(({ id, name, content }) => ({ id, name, content })),
    };
};
Eustachio
  • 1
  • 1

1 Answers1

0

.json method returns you any type, because of this, you have such a mess. You need to update this line:

const data = res.json() as {docs: JokesDataItems[]}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Nuriddin
  • 1
  • 1