1. 简介
TypeScript 是 JavaScript 的超集,通过类型注解提供编译时的类型检查,能够有效提升代码的可维护性。
2. 使用 ts 编写代码
我们新建一个目录
···
mkdir webpack-ts && cd webpack-ts
npm init -y
npm i webpack webpack-cli -D
···
我们从官网 copy 一段实例代码:
// index.ts
// There are quite a few ways to declare a function in
// JavaScript. Let's look at a function which adds two
// numbers together:
// Creates a function in global scope called addOldSchool
function addOldSchool(x, y) {
return x + y;
}
// You can move the name of the function to a variable
// name also
const anonymousOldSchoolFunction = function(x, y) {
return x + y;
};
// You can also use fat-arrow shorthand for a function
const addFunction = (x, y) => {
return x + y;
};
// We're going to focus on the last one, but everything
// applies to all three formats.
// TypeScript provides additional syntax which adds to a
// function definition and offers hints on what types
// are expected by this function.
//
// Up next is the most open version of the add function, it
// says that add takes two inputs of any type: this could
// be strings, numbers or objects which you've made.
const add1 = (x: any, y: any) => {
return x + y;
};
add1("Hello", 23);
// This is legitimate JavaScript (strings can be added
// like this for example) but isn't optimal for our function
// which we know is for numbers, so we'll convert the x and
// y to only be numbers.
const add2 = (x: number, y: number) => {
return x + y;
};
add2(16, 23);
add2("Hello", 23);
// Great. We get an error when anything other than a number
// is passed in. If you hover over the word add2 above,
// you'll see that TypeScript describes it as:
//
// const add2: (x: number, y: number) => number
//
// Where it has inferred that when the two inputs are
// numbers the only possible return type is a number.
// This is great, you don't have to write extra syntax.
// Let's look at what it takes to do that:
const add3 = (x: number, y: number): string => {
return x + y;
};
// This function fails because we told TypeScript that it
// should expect a string to be returned but the function
// didn't live up to that promise.
const add4 = (x: number, y: number): number => {
return x + y;
};
// This is a very explicit version of add2 - there are
// cases when you want to use the explicit return type
// syntax to give yourself a space to work within before
// you get started. A bit like how test-driven development
// recommends starting with a failing test, but in this case
// it's with a failing shape of a function instead.
// This example is only a primer, you can learn a lot more
// about how functions work in TypeScript in the handbook and
// inside the Functional JavaScript section of the examples:
//
// https://www.typescriptlang.org/docs/handbook/functions.html
// example:function-chaining
// And to continue our tour of JavaScript essentials,
// we'll look at how code flow affects the TypeScript types:
// example:code-flow
如果我们把这段代贴到 ide,可以发现 add2,add3 都有报错提示,因为 Ts 对代码进行检查,能够让我们提前发现代码中不符合约束的地方。
3. 编译 ts 代码
当然,这段代码是无法直接运行的,我们需要将其编译。如下:
npm i ts-loader typescript -D
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};
"build": "webpack"
npm run build
如下:

可以看到提示我们 tsconfig.json 为空。查询 ts-loader 我们知道,需要为 ts 编译指定一个 tsconfig-json 配置文件,在这里查看完整的编译器选项列表。
如下:
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES5",
"allowJs": true
}
}
配置含义如下:



我们重新编译,如下:

可以看到,编译的过程中,依然会为我们检查代码的正确性,防止我们并未使用支持 ts 校验的 ide,或者遗漏了错误提示。我们修改 index.ts 如下:
// index.ts
const add4 = (x: number, y: number): number => {
return x + y;
};
重新编译,如下:


4. 第三方模块的类型检测
如果我们的代码中引入了第三方模块,ts 是否能够帮助我们对其进行检测呢?
npm i lodash -S
// index.ts
import _ from 'lodash';
const join1 = (x: string, y: string): string => {
return _.join([x, y], '-');
};
const join2 = (x: string, y: string): string => {
return _.join(x, y, ' ');
};
可以看到,我们的 join2 明显是存在问题的,_.join 第一个参数应该是一个要连接的数组,第二个参数是连接符,可是这里 ide 并没有提示,打包后文件也能正常编译,但是使用的时候会得到非预期的结果。要想让 ts 对 lodash 生效,我们还需要安装一个模块:
cnpm i @types/lodash -D
此时我们可以看到 ts 报错

修复如下:

还是有报错,继续修复:

好了,现在没有报错了。从上面可以看到,使用第三方库时,我们还需要安装对应的 @types 类型文件,那么如何确定一个三方模块是否有 types 文件呢?可以访问如下地址: TypeSearch 进行搜索。
参考
https://www.typescriptlang.org/docs/home.html
https://www.runoob.com/typescript/ts-tutorial.html
https://www.tslang.cn/docs/handbook/tsconfig-json.html
https://github.com/TypeStrong/ts-loader
https://www.tslang.cn/docs/handbook/compiler-options.html
网友评论