Migrating from JavaScript to TypeScript
Gradually migrate existing JavaScript projects to TypeScript.
Migration strategies
- Add tsconfig.json
- Rename .js to .ts
- Gradually add type annotations
- Enable strict mode
Configure tsconfig.json
tsconfig.json
{
"compilerOptions"
:
{
// Initial stage: loose configuration
"target"
:
"ES2020"
,
"module"
:
"commonjs"
,
"strict"
:
false
,
"noImplicitAny"
:
false
,
"strictNullChecks"
:
false
,
"skipLibCheck"
:
true
,
// Allow JS files
"allowJs"
:
true
,
"checkJs"
:
false
,
// Output directory
"outDir"
:
"./dist"
,
"rootDir"
:
"./src"
}
,
"include"
:
[
"src/**/*"
]
,
"exclude"
:
[
"node_modules"
,
"dist"
]
}
Gradually enable strict checks
Enable in stages
// Stage 1: basic migration
{
"compilerOptions"
:
{
"strict"
:
false
,
"noImplicitAny"
:
false
}
}
// Stage 2: enable type checking
{
"compilerOptions"
:
{
"strict"
:
true
,
"noImplicitAny"
:
true
,
"strictNullChecks"
:
true
}
}
// Stage 3: full strictness
{
"compilerOptions"
:
{
"strict"
:
true
,
"noImplicitAny"
:
true
,
"strictNullChecks"
:
true
,
"strictFunctionTypes"
:
true
,
"strictPropertyInitialization"
:
true
}
}
JSDoc type annotations
Add types in JavaScript using JSDoc.
utils.js
/**
* @param {number} a
* @param {number} b
* @returns {number}
*/
function
add
(
a
,
b
)
{
return
a
b
;
}
/**
* @typedef {Object} User
* @property {number} id
* @property {string} name
* @property {string} email
*/
/**
* @param {number} id
* @returns {Promise
*/
function
getUser
(
id
)
{
return
fetch
(
`
/
api
/
users
/
$
{
id
}
`
)
.
then
(
r
=>
r.
json
(
)
)
;
}
Running result:
JSDoc 注释添加成功
Type declaration files
Create declarations for modules without type definitions.
src/types/my-module.d.ts
declare module
"my-module"
{
export
function
doSomething
(
param
:
string
)
:
void
;
export
class
MyClass
{
constructor
(
options
:
{
name
:
string
}
)
;
name
:
string
;
}
}
The declare keyword
Example
// Declare a global variable
declare
var
GLOBAL_CONFIG
:
{
apiUrl
:
string
;
version
:
string
;
}
;
// Declare a global function
declare
function
myFunction
(
param
:
string
)
:
void
;
// Declare a namespace
declare namespace MyNamespace
{
function
doSomething
(
)
:
void
;
}
// Use
console.
log
(
GLOBAL_CONFIG.
apiUrl
)
;
myFunction
(
"hello"
)
;
MyNamespace.
doSomething
(
)
;
Running result:
声明成功
Migration tools
- **tsc --allowJs:** compile JS files
- **checkJs:** check JS types
- **// @ts-check:** type checking for a single file
- **// @ts-ignore:** ignore errors
legacy.js
// @ts-check
// @ts-ignore
var
result
=
someLegacyFunction
(
)
;
Best Practices
- Start migrating from key modules
- Add unit tests
- Gradually enable strict mode
- Use JSDoc comments
- Create type declaration files
Summary
- **Incremental:** migrate step by step
- **JSDoc:** type annotations
- Declaration files:.d.ts
- **Strict mode:** enable in stages