TypeScript/Cypress command which accept only defined value of parameter

Viewed 137

I wrote cypress command with parameter and I would like to change it that function accept only certain values, e.g. I would like that columnValue can be only 'xxx' or 'yyy' or 'zzz'. How can I do it?

Cypress.Commands.add('addColumnAsDimension', (columnName: string) => {
  chartMenu.addColumnButton.click();
  chartMenu.columnNameButton(columnName).click();
  chartMenu.addAsDimensionButton.click();
});

1 Answers

You can use a union type for that:

type Column = 'xxx' | 'yyy' | 'zzz'

Cypress.Commands.add('addColumnAsDimension', (columnName: Column) => {
  chartMenu.addColumnButton.click();
  chartMenu.columnNameButton(columnName).click();
  chartMenu.addAsDimensionButton.click();
});

Also, if you want the complier to check your custom Cypress method invocation, you have to add a type definition for the method as well:

declare namespace Cypress {
  interface Chainable<Subject> {
       addColumnAsDimension(columnName: Column): void
    }
}

Now the compiler checks your arguments: enter image description here

Related