I have a TypeScript type like this:
type Api = {
createItem: (name: string) => Promise<Item>;
getItem: (id: number) => Promise<Item>;
updateItem: (item: Item) => Promise<Item>;
deleteItem: (id: number) => Promise<void>;
};
And I'm trying to figure out how to convert it to the following:
type Api = {
createItem: (name: string) => { type: 'success'; result: Item; } | { type: 'error' };
getItem: (id: number) => { type: 'success'; result: Item; } | { type: 'error' };
updateItem: (item: Item) => { type: 'success'; result: Item; } | { type: 'error' };
deleteItem: (id: number) => { type: 'success' } | { type: 'error' };
};
I think mapping types are a way to go here:
type NewApi = {
[_ in keyof Api]: (???) => { type: 'success'; result: ??? } | { type: 'error' }
};
I'm unable to figure out how to fill in the blanks there though. I'm not even sure it is possible to do that.
The reason I need this type is that I am building a gateway proxy and the actual implementation of the type will be an actual Proxy
object intercepting the member accesses, mocking their values with another proxy which traps function invocation for a change and returns the above union type.
The implementation part is fine, but I can't seem to be able to get the type for it to get Intellisense working.
You can make use of typescripts Parameters and ReturnType types
type NewApi = {
[K in keyof Api]: (...args: Parameters<Api[K]>) => { type: 'success'; result: ReturnType<Api[K]> } | { type: 'error' }
};
Please see this playground .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.