Item 78: Pay Attention to Compiler Performance
May 10, 2024 ยท View on GitHub
Things to Remember
- There are two forms of TypeScript performance issues: build performance (
tsc) and editor latency (tsserver). Recognize the symptoms of each and direct your optimizations accordingly. - Keep type checking separate from your build process.
- Remove dead code and dependencies, and be on guard for code bloat in type dependencies. Use a treemap to visualize what TypeScript is compiling.
- Use incremental builds and project references to reduce the work
tscdoes between builds. - Simplify your types: avoid large unions, use
interfaceextension rather than intersection types, and consider annotating function return types.## Code Samples
// hello.ts
console.log('Hello World!');
function foo() {}
// ~~~ 'foo' is declared but its value is never read.
export function bar() {}
// src/fib.ts
export function fib(n: number): number {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
// test/fib.test.ts
import {fib} from '../src/fib';
describe('fib', () => {
it('should handle base cases', () => {
expect(fib(0)).toEqual(0);
expect(fib(1)).toEqual(1);
})
it('should handle larger numbers', () => {
expect(fib(2)).toEqual(1);
expect(fib(3)).toEqual(2);
expect(fib(4)).toEqual(3);
expect(fib(5)).toEqual(5);
expect(fib(16)).toEqual(987);
});
});
type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
type Year = `2${Digit}${Digit}${Digit}`;
const validYear: Year = '2024';
const invalidYear: Year = '1999';
// ~~~~~~~~~~~ Type '"1999"' is not assignable to type
// '"2000" | "2001" | "2002" | ... 996 more ... | "2999"'.