TypeScript Mapped Types

Hey. I have this type which uses mapped types to generate this other type. It works a little bit, but I'd like it to generate a different type of type union.
1 Reply
domi?
domi?2y ago
const functions = [
{
type: 'on',
path: 'test1',
callback: (_: Electron.IpcMainEvent, __: number) => 0
},
{
type: 'on',
path: 'test2',
callback: (_: Electron.IpcMainEvent, __: string) => '0'
}
] as const;


type Renderer<Functions extends IPCFunction> = {
[Fn in Functions as 'send']: (channel: Fn['path'], ...args: Parameters<Fn['callback']>) => void;
};

type RouterType = typeof functions;

let renderer: Renderer<RouterType[number]>;

renderer.send();
const functions = [
{
type: 'on',
path: 'test1',
callback: (_: Electron.IpcMainEvent, __: number) => 0
},
{
type: 'on',
path: 'test2',
callback: (_: Electron.IpcMainEvent, __: string) => '0'
}
] as const;


type Renderer<Functions extends IPCFunction> = {
[Fn in Functions as 'send']: (channel: Fn['path'], ...args: Parameters<Fn['callback']>) => void;
};

type RouterType = typeof functions;

let renderer: Renderer<RouterType[number]>;

renderer.send();
The type of renderer.send is (channel: "test2" | "test1", ...args: [_: Electron.IpcMainEvent, __: number] | [_: Electron.IpcMainEvent, __: string]) => void. It's nice but it could be improved. Is there any way to make it ((channel: "test1", ...args: [_: Electron.IpcMainEvent, __: number]) => void) | ((channel: "test2", ...args: [_: Electron.IpcMainEvent, __: string]) => void)? I ended up mapping the types into an object first, then just grab each of its values and putting it into a union and it worked fine 👍
Want results from more Discord servers?
Add your server