TypeScript + Node.js in Practice
TypeScript is widely used in Node.js back-end development. This tutorial introduces the configuration and use of TypeScript in Node.js projects.
Using TypeScript makes Node.js code safer and easier to maintain, especially suitable for medium and large back-end projects.
View the Node.js tutorial:https://www.runoob.com/nodejs/nodejs-tutorial.html
Why use TypeScript in Node.js
Node.js projects usually involve complex business logic and data processing, and the amount of code grows rapidly.
Using TypeScript can: provide compile-time type checking to reduce runtime errors; leverage IDE intelligent hints to improve development efficiency; make code more readable and maintainable.
Many large Node.js projects (such as NestJS) recommend or default to TypeScript.
Advantages:TypeScript's static type checking can detect potential problems during development, which is more efficient than runtime debugging.
Project initialization
First, initialize the Node.js project and install TypeScript-related dependencies.
Initialize a project
Initialize npm
npm init
y
Install TypeScript and Node.
js
Type definitions
D means install as a development dependency
npm install
D typescript
@
types
/
node ts
node nodemon
Initialize tsconfig.
json
npx tsc
--
init
Explanation:
@types/nodeprovides type definitions for Node.js APIs,ts-nodecan run TypeScript files directly,nodemonwatches for file changes and restarts automatically.
tsconfig.json configuration
Configure TypeScript compiler options optimized for Node.js projects.
tsconfig.json
{
"compilerOptions"
:
{
// Compilation target: ES2020
"target"
:
"ES2020"
,
// Module system: CommonJS (natively supported by Node.js)
"module"
:
"commonjs"
,
// Enabled libraries
"lib"
:
[
"ES2020"
]
,
// Output directory
"outDir"
:
"./dist"
,
// Root directory of source code
"rootDir"
:
"./src"
,
// Strict mode (always on)
"strict"
:
true
,
// ES module interop
"esModuleInterop"
:
true
,
// Skip library checking
"skipLibCheck"
:
true
,
// Enforce consistent file name casing
"forceConsistentCasingInFileNames"
:
true
,
// Module resolution strategy
"moduleResolution"
:
"node"
,
// Generate declaration files
"declaration"
:
true
}
,
// Files to compile
"include"
:
[
"src/**/*"
]
,
// Excluded files
"exclude"
:
[
"node_modules"
,
"dist"
]
}
Recommended configuration:Node.js projects are recommended to use
module: "commonjs", which is the module system natively supported by Node.js.
Defining types
Define the project's type interfaces in the types directory.
src/types/index.ts
// User type definition
export
interface
User
{
id
:
number
;
// The user ID
name
:
string
;
// Username
:
string
;
createdAt
:
Date
;
// Creation time
}
// Data transfer object for creating a user
export
interface
CreateUserDTO
{
name
:
string
;
// Username (required)
:
string
;
// Email (required)
password
:
string
;
// Password (required)
}
// API response type (generic)
export
interface
ApiResponse
<
T
{
success:
boolean
;
// Whether it is successful
data
?:
T
;
// Data on success
error
?:
string
;
// Error message on failure
}
Type definitions:Place type definitions centrally in the types directory for easier maintenance and reuse.
Implementing services
Implement business logic in the services directory using the defined types.
src/services/userService.ts
// Import type definitions
import
{
User
,
CreateUserDTO
,
ApiResponse
}
from
"../types"
;
// User service class
class
UserService
{
// User list (in-memory storage)
private users
:
User
[
]
=
[
]
;
// Next user ID
private nextId
=
1
;
// Create a user
createUser
(
dto
:
CreateUserDTO
)
:
ApiResponse
<
User
{
try
{// Create the user object
const
user
:
User
=
{
id
:
this
.
nextId
++,
name
:
dto.
name
,
:
dto.
,
createdAt
:
new
Date
(
)
}
;
this
.
users
.
push
(
user
)
;
return
{
success
:
true
,
data
:
user
}
;
}
catch
(
error
)
{
return
{
success
:
false
,
error
:
"Failed to create user"
}
;
}
}
// Get a single user
getUser
(
id
:
number
)
:
ApiResponse
<
User
{
const
user
=
this.
users
.
find
(
u
=>
u.
id
===
id
)
;
if
(
!
user
)
{
return
{
success
:
false
,
error
:
"User does not exist"
}
;
}
return
{
success
:
true
,
data
:
user
}
;
}
// Get all users
getAllUsers
(
)
:
ApiResponse
<
User
[
]
{
return
{
success:
true
,
data
:
this
.
users
}
;
}
}
// Export a singleton
export
default
new
UserService
(
)
;
Running result:
UserService 实例化成功
Service layer:Business logic is concentrated in the service layer, making it easier to test and reuse.
Creating API routes
Use the Express framework to create a RESTful API.
src/index.ts
import
express
,
{
Request
,
Response
}
from
"express"
;
import
userService from
"./services/userService"
;
// Create an Express app
const
app
=
express
(
)
;
// Parse the JSON request body
app.
use
(
express.
json
(
)
)
;
// Get all users
app.
get
(
"/api/users"
,
(
req
:
Request
,
res
:
Response
)
=>
{
const
result
=
userService.
getAllUsers
(
)
;
res.
json
(
result
)
;
}
)
;
// Get a single user
app.
get
(
"/api/users/:id"
,
(
req
:
Request
,
res
:
Response
)
=>
{
const
id
=
parseInt
(
req.
params
.
id
)
;
const
result
=
userService.
getUser
(
id
)
;
res.
json
(
result
)
;
}
)
;
// Create a user
app.
post
(
"/api/users"
,
(
req
:
Request
,
res
:
Response
)
=>
{
const
result
=
userService.
createUser
(
req.
body
)
;
res.
json
(
result
)
;
}
)
;
const
PORT
=
3000
;
app.
listen
(
PORT
,
(
)
=>
{
console.
log
(
`Server running at http
:
//localhost:${PORT}`);
}
)
;
Running result:
服务器运行在 http://localhost:3000
Type hints:Use
RequestandResponsetype, the IDE will provide complete property hints.
package.json scripts
Configure npm scripts to simplify the development workflow.
package.json
{
"scripts"
:
{
// Compile TypeScript
"build"
:
"tsc"
,
// Run the compiled JavaScript
"start"
:
"node dist/index.js"
,
// Development mode: use nodemon to watch for changes and restart automatically
"dev"
:
"nodemon --exec ts-node src/index.ts"
,
// Run tests
"test"
:
"jest"
}
}
Development efficiency:Use
npm run devcan automatically restart the server after code changes.
Notes
- **Strict mode:** always enable strict: true
- **Module choice:** Node.js projects use commonjs
- **Type definitions:** install @types/node to get API types
- **Development tools:** use ts-node for hot reloading
Best practices:Keep type definitions separate from business logic for easier testing and maintenance.
Summary
TypeScript is an excellent choice for Node.js back-end development.
- **Project configuration:** use tsconfig.json to configure compiler options
- **Type definitions:** centrally manage interfaces in the types directory
- **Service layer:** separate business logic from routes
- **Routes:** use Express to create a RESTful API
- **Development tools:** ts-node and nodemon improve development efficiency
Note:New projects can use TypeScript directly, while older projects can migrate gradually.