Make test automation easier with better feedback for parameters with TypeScript

We can make it easier to automate tests by giving feedback if incorrect values are passed as parameters. Developers can get feedback when they try to pass an invalid parameter if I use union types when using TypeScript. I have been using TypeScript to automate tests with Playwright.

We often pass strings to functions as parameters. Sometimes this is because any string can be passed as a parameter. Other times there are only a limited number of strings that can be passed, such as the name of a country. If only a limited number of strings can be passed and we are using Typescript to write our tests, we can pass a union type instead of a string. 


A union type can be used to create a type that consists of only the strings that can be passed as parameters. Union types can be used when a type can be more than one type, for example, a union type could contain a string and a number. The types held in a union type can be literal types such as a string, for example, “cricket”. The union type is an ‘or’ type, so the type will be: ‘string1’ | ’string2’. An example of a union type could be defined in a .d.ts file like this:

The file containing the union type can be imported into your file like this:

The type can then be passed to the function checkBowlingAverage as the parameter bowler:

If a developer enters an invalid value such as ‘swxxing’ for the parameter bowler Visual Studio code will show the error:

If the developer’s mouse hovers overs over the invalid parameter, Visual Studio Code displays a message which shows the valid values. This makes it easy for the developer to correct the invalid parameter.

Execute Program has a lesson on Type Unions, and FrontendMasters has a lesson on Union Types. Both lessons have helped me get a better understanding of union types.

It is helpful if a larger group of people can automate tests and so it is useful to make it as easy as possible for tests to be automated. Using union types can help make it easier to automate tests because feedback is given if an incorrect value is passed.

Published by Mike Harris

Mike has been a testing professional for over 20 years. He has been a Test Lead and has also worked as a part of waterfall, lean and agile teams. He has set up and led a Testing Community of Practice and been part of a successful agile transition. He is Vice-Chair of the British Computer Society’s Specialist Interest Group in Software Testing. He also contributed to the e-books Testing Stories and How Can I test This?

Leave a comment

Design a site like this with WordPress.com
Get started