The recent TypeScript 3.9 release primarily focuses on performance and stability, but it does include some language updates that are worth a closer look.

Expansion of uncalled function checks

Continuing its quest to save you from yourself, TypeScript 3.9 expands on the uncalled function checks that were introduced in version 3.7. These checks report when a function is used within an if condition without being called, like:

const isValid() => someGlobalValue > 10;
let answer: string;
if (isValid) {      // error because isValid isn't called
  answer = 'yes';
} else {
  answer = 'no';
}

The latest version brings this functionality to ternary operators as well:

const answer1 = isValid ? 'yes' : 'no';    // error
const answer2 = isValid() ? 'yes' : 'no';  // no error

This type of functionality is a perfect example of the language going above and beyond to warn developers about potential problems with their code, especially when those problems aren’t syntax or type-related.

The @ts-expect-error comment

The // @ts-expect-error comment provides a way for developers to specify that the next line should contain a type error. If that’s the case, TypeScript will suppress any error for that line. If the comment exists and there is no error, TypeScript will throw an error because you specified that one was expected.

This comment can be particularly useful when writing unit tests. Suppose you have a function that does some runtime checking of the data. In order to verify that the runtime checking handles improper input properly, you might need to pass the function some data that it doesn’t expect and that would fail argument type-checking. The @ts-expect-error comment will suppress the resulting type error so that the invalid data can be tested.

function add(a: number, b: number) {
   if (typeof a === 'string' || typeof b === 'string') {
       return 'fail';
   }
}

it('should return "fail" when a string is passed', () => {
    // @ts-expect-error
    expect(add(2, '2')).toBe('fail');
});

Other TypeScript 3.9 changes

There are several other updates in this release that improve TypeScript’s performance and stability, providing a more solid base for the next version. The compiler is quite a bit faster, reducing some project build times by 50%. TypeScript’s IDE integration has also improved, and an annoying Promise.all typing issue was fixed.

For a deeper dive into TypeScipt in general, check out our definitive TypeScript Guide. Or, feel free to reach out to us, if you need a hand. 

Along with these improvements are a few breaking changes, so check the release notes before upgrading. Like us, TypeScript is taking time during the covid-19 quarantine to work on itself, and we can all appreciate that!