TypeScript is not suitable for all projects, but if you want to have Typed JavaScript in your current project, this is probably a great strategy to start with.
TypeScript不适用于所有项目,但是如果您想在当前项目中使用Typed JavaScript,那么这可能是一个很好的策略。
We’ll see how to configure your project to have this support and how to use the JSDoc to add type to your code.
我们将看到如何配置您的项目以具有此支持,以及如何使用JSDoc将类型添加到代码中。
让我们创建我们的项目 (Let’s Create Our Project)
步骤1:在开发依赖项上安装捆绑程序和TypeScript (Step 1: Install a bundler and the TypeScript on dev dependencies)
First, we have to install the TypeScript. The TypeScript will check the types on our code based on the JSDoc. In this example, I will use the microbundle bundler to minify our code and produce ESM, CJS, UMD bundles.
首先,我们必须安装TypeScript。 TypeScript将基于JSDoc检查我们代码上的类型。 在这个例子中,我将使用微束捆绑器来最小化我们的代码,并生成ESM,CJS和UMD捆绑。
$ npm init -y
$ npm i -D typescript microbundle
步骤2:配置TypeScript (Step 2: Configure the TypeScript)
We have to configure the TypeScript to allow .js
files and to check them. For that, create the file tsconfig.json
with the props "allowJs": true
and "checkJs": true
. With the declaration property, it will generate .d.ts
files for every JavaScript file inside your project. The complete tsconfig.json
file is here:
我们必须将TypeScript配置为允许.js
文件并进行检查。 为此,使用道具"allowJs": true
和"checkJs": true
创建文件tsconfig.json
。 使用.d.ts
属性,它将为项目中的每个JavaScript文件生成.d.ts
文件。 完整的tsconfig.json
文件在这里:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"lib": [
"DOM",
"ESNext"
],
"allowJs": true,
"checkJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"declarationMap": true,
"declarationDir": "./dist",
"noEmit": false,
"strict": true,
"suppressImplicitAnyIndexErrors": true,
"noImplicitThis": false,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src"
]
}
Pro tip: For more information about the other
tsconfig.json
properties, please check the documentation.专家提示 :有关其他
tsconfig.json
属性的更多信息,请参阅文档 。
步骤3:创建构建脚本 (Step 3: Create the build script)
The build script will generate all the bundles and type-check our source code.
构建脚本将生成所有捆绑包,然后对我们的源代码进行类型检查。
{
"name": "my-project",
"version": "1.0.0",
"source": "src/index.js",
"main": "dist/my-project.js",
"umd:main": "dist/my-project.umd.js",
"module": "dist/my-project.module.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "microbundle && tsc"
},
"devDependencies": {
"microbundle": "^0.12.3",
"typescript": "^3.9.7"
},
"files": [
"dist",
"src"
]
}
步骤4:编写您的应用程序 (Step 4: write your application)
Now it is time to write your application. In this example, I have a user module where I can save, update, and fetch a user information.
现在是时候编写您的应用程序了。 在此示例中,我有一个用户模块,可以在其中保存,更新和获取用户信息。
To create our user type we’ll define a JSDoc like this:
要创建我们的用户类型,我们将定义一个JSDoc,如下所示:
/**
* @typedef {Object} User
* @property {number} id
* @property {string} firstName
* @property {string} lastName
* @property {string} role
*/
We use @typedef
to define complex types like User. Within @typedef
, we have the @property
defining the type of each property of the User
object.
我们使用@typedef
定义诸如User之类的复杂类型。 在@typedef
,我们有@property
定义的每个属性的类型User
对象。
Now let’s define the update, save, and get user functions:
现在,让我们定义更新,保存和获取用户功能:
/**
* @param {number} id
* @param {Partial<User>} update
*/
function updateUser(id, update) { }
/**
* Save a user on server
* @param {number} id
* @param {Partial<User>} newUser
*/
function saveUser(id, newUser) { }
/**
* @param {number} id
* @returns {Promise<User>}
*/
function getUser(id) { }
For functions we basically define the params and returns of the function. As we can see, we’re following the same pattern as we defined the User
type, with the JSDoc annotation, the type, and the parameter name. For the return, we only have @returns
and the return type between curly braces.
对于函数,我们基本上定义了函数的参数和返回值。 如我们所见,我们遵循与定义User
类型相同的模式,并带有JSDoc批注,类型和参数名称。 对于返回,我们只有@returns
和花括号之间的返回类型。
Click here to go to see the supported JSDoc annotations.
单击此处以查看受支持的JSDoc批注。
The complete example file:
完整的示例文件:
/**
* @typedef {Object} User
* @property {number} id
* @property {string} firstName
* @property {string} lastName
* @property {string} role
*/
/** */
export default (function () {
/**
* @param {number} id
* @param {Partial<User>} update
*/
function updateUser(id, update) {
const user = getUser(id);
const newUser = { ...user, ...update };
saveUser(id, newUser);
}
/**
* Save a user on server
* @param {number} id
* @param {Partial<User>} newUser
*/
function saveUser(id, newUser) {
// saving user on server
}
/**
* @param {number} id
* @returns {Promise<User>}
*/
function getUser(id) {
return new Promise((resolve) => {
// simulate geeting a user from server
const user = {
id: 1234,
firstName: "Cesar",
lastName: "Alvarenga",
role: "Software Engineer",
};
resolve(user);
});
}
return {
getUser,
saveUser,
updateUser,
};
})();
步骤5:建立专案 (Step 5: build the project)
To build the project, we just run:
要构建项目,我们只需运行:
$ npm run build
And in this example, it will generate the files below:
在此示例中,它将生成以下文件:
.
├── index.d.ts
├── index.d.ts.map
├── my-project.js
├── my-project.js.map
├── my-project.modern.js
├── my-project.modern.js.map
├── my-project.module.js
├── my-project.module.js.map
├── my-project.umd.js
└── my-project.umd.js.map
.d.ts
file contains the TypeScript types..d.ts
文件包含TypeScript类型。.js
file is your JavaScript source file minified..js
文件是您JavaScript源文件。.modern.js
bundle specially designed to work in all modern browsers..modern.js
捆绑软件专门设计用于所有现代浏览器 。.module.js
bundle ESM (javascript module)..module.js
捆绑ESM(javascript模块)。.umd.js
bundle UMD (Universal Module Definition)..umd.js
捆绑了UMD(通用模块定义)。
结论 (Conclusion)
Now you have a codebase to start typing your JavaScript projects. To get more insights about how you can use JSDoc to type your code, watch this Paul Lewis video https://www.youtube.com/watch?v=YHvqbeh_n9U. And check this project built with this strategy https://github.com/cesarwbr/loadx.
现在,您有了一个代码库,可以开始键入JavaScript项目。 要获取有关如何使用JSDoc键入代码的更多见解,请观看Paul Lewis视频https://www.youtube.com/watch?v=YHvqbeh_n9U 。 并检查使用此策略构建的该项目https://github.com/cesarwbr/loadx 。