Patrick Desjardins Blog
Patrick Desjardins picture from a conference

TypeScript and Restricting String to Interface Members

Posted on: 2017-10-17

Imagine the scenario where you have an interface with many members. Each of them is a boolean and your React component allows you to toggle with a checkbox the value of them. You have a single method that will dispatch the action to your Redux/Flux cycle. How can you make your code strong enough and still be flexible to not having 1 function per member?

The solution resides that we do not one to allow every string but just a finite set of string which is the members' name of a specific interface.

public render(): JSX.Element { 
  // ... 
  <input type="checkbox" 
    checked={this.props.myModel.member1} 
    onClick={(e) => { this.onToggle("member1"); }} 
  /> 
  // ... 
} 

The click method won't ask for a string, but for a key of the model.

private onToggle(filterName: keyof MyModel) { 
  this.props.onToggle(filterName); 
} 

This little difference makes the whole system being flexible since it allows to type string, but strict in a way that we have a defined set of potential value. The set is also dynamic. If you rename a member, add or remove a member from the interface, TypeScript will come in play and warn if something is invalid.

In this article, we saw a way to use string to indicate which value to change. Since interfaces are stripped out at transpilation time, there is some case like the one presented that providing a string is the only solution. TypeScript allows the use of keyof to extract a set of string from an interface which allows having a finite set of accepted results and hence reinforce your code by eliminate wrong inputs.