Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

typescript - How to get default type which function returns by custom TypeMap

I have function which returns promise with type which provided by generic

const api = <Model>(url: string) => Promise<Model>

For now I always need to set Type of returned data

const data = await api<{id: string, name: string}>('google.com')

How can I check if url includes in CustomMap then returns type from my map.

For example:

interface CustomMap {
  'google.com': {id: string, name: string}
  'amazon.com': {count?: number}
}

So I wanna get {id: string, name: string} when I call api('google.com')

If url not defined in map I want to get Type from input Generic

const data = await api('youtube.com') // error: Must provided some type
const data = await api<YoutubeResponse>('youtube.com') // ok
question from:https://stackoverflow.com/questions/66055432/how-to-get-default-type-which-function-returns-by-custom-typemap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are other ways to structure this that might be better, but what you are asking for is pretty straight-forward. I am separating the arguments for the domain and the path so that you can get autocomplete support on the domain name. I am saying that the domain must be one of the keys in your custom map, so you'll get an error if you try to access something with an unknown return type.

This typedApi function takes the domain and the path and then calls the root api function with the correct return type based on the domain.

const typedApi = <Domain extends keyof CustomMap>(domain: Domain, path: string): Promise<CustomMap[Domain]> => {
  return api<CustomMap[Domain]>(`https://${domain}${path}`);
}
// Promise<{ id: string; name: string; }>
const gData = typedApi('google.com', '/some-path');

// Promise<{ count?: number }>
const aData = typedApi('amazon.com', '/some-path');

Playground Link


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...