Currently in the process of developing an SDK for a Rest API that includes an embed request parameter to fetch additional resources and add them to the response. I am exploring if there is a way, using Typescript, to extract these embed parameters while defining the return type for getImage
. I have made progress with Generics, but the solution isn't as elegant as I had hoped. The following example is simplified, but I am seeking a solution that can be applied to multiple methods with varying embed options. Any advice would be greatly appreciated.
interface Type {
ext: string
}
interface User {
id: number
name: string
}
interface Image {
id: number
name: string
}
function getImage(id: number, embed?: string | string[]) {
// implementation of making API request goes here
}
No embeds included
getImage(1)
{
id: 1,
name: 'my-image'
}
Single embed provided
getImage(1, 'type')
{
id: 1,
name: 'my-image',
type: {
ext: '.png'
}
}
Array of embeds specified
getImage(1, ['type', 'user])
{
id: 1,
name: 'my-image',
type: {
ext: '.png'
},
user: {
id: 2,
name: 'John Doe'
}
}