Home > Back-end >  TypeScript Parameters is throwing error when used dynamically
TypeScript Parameters is throwing error when used dynamically

Time:11-20

I am trying to get parameters of the electron dialog but I am getting two errors:

Type 'Dialog[U]' does not satisfy the constraint '(...args: any) => any'.

Type 'U' cannot be used to index type 'Dialog'.

I am doing this:

declare global {
  interface Window {
    dialogOpen: <T, U = keyof Electron.Dialog>(name: U, ...options: Parameters<Electron.Dialog[U]>) => Promise<T>;
  }
}

I then tried to manually type the value like this and I get no error.

type Test = Parameters<Electron.Dialog['showOpenDialog']>;

What am I doing wrong when I try to dynamically type the parameters?

CodePudding user response:

Your problem is simply that the generic type parameter U merely defaults to keyof Electron.Dialog (using the X = Y notation); it is not at all constrained to keyof Electron.Dialog (using the X extends Y notation) . It is not constrained at all, and therefore Electron.Dialog[U] might not be a valid indexed access.

If you fix that:

interface Window {
  dialogOpen: <T, U extends keyof Electron.Dialog>(
    name: U, ...options: Parameters<Electron.Dialog[U]>) => Promise<T>;
}

then it compiles with no error. If you want you can keep the default also, like

interface Window {
  dialogOpen: <T, U extends keyof Electron.Dialog = keyof Electron.Dialog>(
    name: U, ...options: Parameters<Electron.Dialog[U]>) => Promise<T>;
}

depending on your use case.

Playground link to code

  • Related