Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Performance Optimization

TypeScript Performance Optimization

Performance optimization of TypeScript projects involves compilation speed, runtime performance, code size, and other aspects.

This tutorial introduces common performance optimization techniques to help build more efficient TypeScript applications.


Dimensions of TypeScript performance optimization Compilation Speed Incremental build | skipLibCheck Runtime performance Type inference | Avoid any Bundle Size Tree Shaking | Lazy loading Key optimization strategies skipLibCheck Skip library type checking incremental Incremental compilation Project References Project references

Why performance optimization is needed

Although TypeScript provides a powerful type system, improper use can affect compilation speed and runtime performance.

Compiling a large project may take several minutes, seriously affecting the development experience.

The configurations and techniques introduced in this tutorial can significantly improve the performance of TypeScript projects.

Optimization goals:Faster compilation, smaller bundle size, and higher runtime performance.


Compilation configuration optimization

Improve compilation speed by optimizing the tsconfig.json configuration.

tsconfig.json optimization configuration

{

   

"compilerOptions"

:

{

       

// Enable incremental compilation and save the previous compilation information

       

"incremental"

:

true

,

       

// Skip type checking of node_modules

       

// Greatly improve compilation speed

       

"skipLibCheck"

:

true

,

       

// Skip generation of declaration files (only generated in the final build)

       

"noEmit"

:

true

,

       

// Enable fast incremental build

       

"assumeChangesOnlyAffectDirectDependencies"

:

true

,

       

// Execute in parallel

       

"parallel"

:

true

,

       

// Enable caching

       

"tsBuildInfoFile"

:

".tsbuildinfo"

,

       

// Files that do not need to be parsed

       

"exclude"

:

[

           

"node_modules"

,

           

"dist"

,

           

"build"

,

           

"**/*.test.ts"

       

]

   

}

}

skipLibCheck:This is the most important optimization option and can reduce compilation time by more than 50%.


Project reference optimization

Use project references to split a large project into small modules for incremental compilation.

packages/utils/tsconfig.json

{

   

// Extend the base configuration

   

"extends"

:

"../../tsconfig.base.json"

,

   

"compilerOptions"

:

{

       

"composite"

:

true

,

       

"outDir"

:

"./dist"

,

       

"declaration"

:

true

,

       

"declarationMap"

:

true

   

}

,

   

"include"

:

[

"src/**/*"

]

,

   

"exclude"

:

[

"node_modules"

,

"dist"

]

}

composite:Once enabled, TypeScript generates a .tsbuildinfo file to speed up subsequent compilations.


Type inference optimization

Make full use of TypeScript's type inference and avoid excessive annotations.

< h2 class="example">Example

// Bad practice: over-annotating types

const

name

:

string

=

"Alice"

;

const

age

:

number

=

25

;

const

isActive

:

boolean

=

true

;

// Good practice: leverage type inference

const

name

=

"Alice"

;

const

age

=

25

;

const

isActive

=

true

;

// Function return types can be omitted (TypeScript infers them automatically)

function

add

(

a

:

number

,

b

:

number

)

{

   

return

a

b

;

}

// Use type inference for complex objects

const

user

=

{

    id

:

1

,

    name

:

"Bob"

,

    email

:

"bob@example.com"

}

;

// TypeScript will infer:

// { id: number; name: string; email: string }

// Explicit annotations are only needed when type inference is inaccurate

const

elements

:

HTMLElement

[

]

=

[

]

;

Reduce annotations:TypeScript's type inference is already very smart; in most cases explicit type annotations are unnecessary.


Avoid using any

Using any loses the advantage of type checking and affects runtime performance.

Example

// Bad practice: using any

function

processData

(

data

:

any

)

:

any

{

   

return

data.

value

;

}

// Good practice: using unknown or specific types

function

processData

<

T

extends

{

value

:

string

}

(

data

:

T

)

:

string

{

   

return

data.

value

;

}

// If you really don't know the type, use unknown

function

parseJSON

(

json

:

string

)

:

unknown

{

   

return

JSON.

parse

(

json

)

;

}

// Perform type checking when using it

const

data

=

parseJSON

(

'{"key": "value"}'

)

;

if

(

typeof

data

===

"object"

&&

data

!==

null

)

{

   

const

obj

=

data as

{

key

:

string

}

;

    console.

log

(

obj.

key

)

;

}

// Better practice: use generics

function

identity

<

T

(

value

:

T

)

:

T

{

   

return

value

;

}

const

result

=

identity

(

"hello"

)

;

console.

log

(

"Result: "

result

)

;

unknown vs any:unknown is the type-safe version of any and requires type checking before use.


Interfaces vs type aliases

Choose the appropriate type definition approach based on the scenario.

Example

// Interfaces: suitable for defining object types, support declaration merging

interface

User

{

    id

:

number

;

    name

:

string

;

}

// Extend an interface

interface

User

{

    email

:

string

;

}

// Type aliases: suitable for union types, tuples, and function types

type ID

=

string

|

number

;

type Status

=

"pending"

|

"success"

|

"error"

;

type Callback

=

(

data

:

string

)

=>

void

;

// Utility types usually use type

type PartialUser

=

Partial

<

User

;

type ReadonlyUser

=

Readonly

<

User

;

// Performance consideration: interfaces usually compile faster than type aliases

// For simple object types, you can use interface

interface

Point

{

    x

:

number

;

    y

:

number

;

}

// For union types, use type

type Shape

=

Circle

|

Square

|

Triangle

;

Selection advice:Use interfaces for object types, type for union types, and type for function types.


Build tool optimization

Configure build tools for optimal performance.

vite.config.ts

// Import vite

import

{

defineConfig

}

from

'vite'

;

import

react from

'@vitejs/plugin-react'

;

// Vite configuration optimization

export

default

defineConfig

(

{

    plugins

:

[

react

(

)

]

,

   

// Build optimization

    build

:

{

       

// Enable code splitting

        rollupOptions

:

{

            output

:

{

               

// Manual chunking

                manualChunks

:

{

                   

'vendor'

:

[

'react'

,

'react-dom'

]

,

                   

'utils'

:

[

'lodash'

,

'axios'

]

               

}

           

}

       

}

,

       

// Minify code

        minify

:

'terser'

,

       

// Generate sourcemap

        sourcemap

:

false

,

       

// Chunk size limit

        chunkSizeWarningLimit

:

500

   

}

,

   

// Development server optimization

    server

:

{

       

// Enable hot update

        hmr

:

{

            overlay

:

true

       

}

   

}

,

   

// Optimize dependency resolution

    optimizeDeps

:

{

        include

:

[

'react'

,

'react-dom'

]

,

        exclude

:

[

'some-large-library'

]

   

}

}

)

;

Code splitting:Use manualChunks to separate large libraries and reduce the main bundle size.


Tree Shaking

Configure modules to support Tree Shaking and eliminate unused code.

src/utils/index.ts

// Use ES module exports to support Tree Shaking

export

function

add

(

a

:

number

,

b

:

number

)

:

number

{

   

return

a

b

;

}

export

function

subtract

(

a

:

number

,

b

:

number

)

:

number

{

   

return

a

b

;

}

export

function

multiply

(

a

:

number

,

b

:

number

)

:

number

{

   

return

a

b

;

}

export

function

divide

(

a

:

number

,

b

:

number

)

:

number

{

   

if

(

b

===

0

)

{

       

throw

new

Error

(

"Cannot divide by zero"

)

;

   

}

   

return

a

/

b

;

}

// Named exports are more favorable to Tree Shaking than default exports

// Wrong: export default prevents Tree Shaking

// export default { add, subtract, multiply, divide };

// Correct: use named exports

console.

log

(

"Utility module loaded"

)

;

Named exports:Using named exports instead of default exports allows build tools to perform Tree Shaking better.


Notes

Best practices:Set up optimization configurations early in development to avoid later refactoring.


Summary

TypeScript performance optimization involves multiple aspects.

Note:Regularly check compilation time and bundle size to continuously optimize project performance.