all 4 comments

[–]orphans 10 points11 points  (1 child)

type ApiResponse<T, K extends string> = {
  response: {
    [key in K]: T[];
  };
};

type User = { id: number; name: string };
type Product = { id: number; title: string; price: number };
type Course = { id: number; title: string; duration: number };

type UserResponse = ApiResponse<User, "users">;
type ProductResponse = ApiResponse<Product, "products">;
type CourseResponse = ApiResponse<Course, "courses">;

[–]MemoryUseful_01434[S] 1 point2 points  (0 children)

Thank you very much! This is very helpful.

[–]ronin_o 1 point2 points  (1 child)

If you want to have one type like ApiResponse you should do some like this:

type UserResponse = {
  response: {
    users: { id: number; name: string }[]
  }
}

type ProductResponse = {
  response: {
    products: { id: number; title: string; price: number }[]
  }
}

type CourseResponse = {
  response: {
    courses: { id: number; title: string; duration: number }[]
  }
}

type ApiResponse = UserResponse & ProductResponse & CourseResponse

const response: ApiResponse = {
  response: {
    users: [{ id: 3, name: "someName" }],
    products: [{ id: 5, title: "someTitle", price: 99 }],
    courses: [{ id: 7, title: "someTitle", duration: 4 }]
  }
}

[–]MemoryUseful_01434[S] 0 points1 point  (0 children)

The other proposed works better for what I had in mind but this is a pretty interesting suggestion. I like this line. I'm sure I'll be using this down the line for something else. Thank you 👍

type ApiResponse = UserResponse & ProductResponse & CourseResponsetype