skip to Main Content

In Remix, how do you explicitly assign return type of async function that is wrapped in json()?

And, yes I know that I can just let typescript infer the return type for me. I want to make it a habit to as much as possible always declare function return types to improve code readability. I did a google search around this topic and majority of answers says its a good practice to always explicitly declare function return type most of the time.

So far this is what I’ve thought of doing and tried:

async (): Promise<T[]> => {
  return json(object)
}
async (): Promise<JsonFunction> => {
  return json(object)
}
async (): Promise<T[] & JsonFunction> => {
  return json(object)
}
async (): Promise<typeof json> & { object: T[] } => {
  return json(object)
}

Result:

Type 'TypedResponse<T[]>' is not assignable to type '...'

Expected Result: Return type should be TypeResponse<T[]> or object: T[] or an intersected type between object type and JsonFunction? This is what I would assume it should be. Please correct me if I am wrong.

2

Answers


  1. Chosen as BEST ANSWER

    I managed to figure it out!

    So my problem was trying to know the type of Remix json() utility function. When hovering over json() function I noticed that the code editor is telling me that the particular function has type of TypedResponse<T> so I must use that Type when explicitly assigning the return type. Not only that the answer I needed was already in front of my face all along, I didn't know until now that VS Code has an option to search for Type Definition for you by pressing right click and selecting 'Go to Type Defininition'.

    Solution:

    import { json, TypedResponse } from "@remix-run/node";
    
    async (): Promise<TypedResponse<T[]> | undefined> => {
      return json(object)
    }
    

  2. The explanation seemed quite vague to me, but as far as I understand you want to declare Return Type for a function which eventually returns response parsed to JSON. In this case you just have to declare the type in generic of Promise type, pointing to what your function will resolve to in the end.

    async function fetchData(): Promise<{ name: string }[]>
    

    Assuming your expected response in array of objects each having only property name which is string e.g [{ name: "Vlad" }]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search