Home > Net >  Use a classes properties as options for a methods parameter
Use a classes properties as options for a methods parameter

Time:06-16

I have a class called Snackbar which has properties and methods within it like this:

export class SnackbarComponent {
  optionA: number;
  option2: string;

  method1(){}
}

I would like to add the properties as keys in the options. I am using [I in SnackbarComponent]: SnackbarComponent[I]; but it is giving me the following errors:

  • A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
  • A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
  • Cannot find name 'I'.ts(2304)
  • Type 'any' cannot be used as an index type.ts(2538)
export class SnackbarService {
  show(message: string, options?: {
    randomString: string;
    [I in SnackbarComponent]: SnackbarComponent[I];
  }): Snackbar {
    // Create instance of SnackbarComponent
    // Set the properties on the SnackbarComponent
  }
}

CodePudding user response:

You're just missing a keyof

export class SnackbarService {
  show(message: string, options?: {
    [K in keyof SnackbarComponent]: SnackbarComponent[K]
  })
  • Related