1
interface IUsers {
  id: number;
  name: string;
}

export const fetchUsers = () =>
  fetch(`/users`).then((res) => res.json());

How do I add IUsers type to fetchUsers response? fetchUsers return [{id:1, name:'fay'}].

7
  • do you mean : fetchUser = () : iUsers => { // your logic } ? Commented Oct 2, 2021 at 2:59
  • @SamridhTuladhar the data is an array of object Commented Oct 2, 2021 at 3:01
  • 1
    then do you mean : fetch(`/users`).then((res) => res.json() as iUsers );? Commented Oct 2, 2021 at 3:02
  • but I can't do that, I got Conversion of type 'Promise<any>' to type 'IUsers' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Commented Oct 2, 2021 at 3:04
  • can you please edit the question with the sample of result of res.json() and what you expect as the final output? Commented Oct 2, 2021 at 3:05

1 Answer 1

1

Assuming that you have already written this:

export interface iUsers {
    id : number
    name : string
}

Modify your method like this:

export const fetchUsers = async () : Promise<{ data : iUsers[] }>  => {
    const response = await fetch(`/users`) ;
    const data : iUsers[]= await response.json() 
    return { data  }
  }

And use it like this :

const { data } = await fetchUsers();

You can hover on your IDE for the hints, it will show that data is an iUsers[]

EDIT This is the shorted version you wanted, which might not match your requirements

export const fetchUsers = async () : Promise<iUsers[] >  => await (await fetch(`/users`)).json() ;

and use it like this :

const data = await fetchUsers()
Sign up to request clarification or add additional context in comments.

8 Comments

it worked! so you can't use destructing with typescript?
you can use it - in fact, that's what i've done here, it's just that you required the result to be in this way, i manipulated it to be so
I mean if it's const { data: PutMyTypeHere } = 'something' is not possible right
How can you reduce 3 lines of your code above in a function to lesser line? you can't right?
I could, it might look uglier, and not match your requirements, let me edit and add that
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.