文章目录
TypeScript简单示例
示例1 接口定义
- 新建目录test
mkdir test
cd test
- 全局安装下载typescript
npm install -g typescript@next
安装了typescript@4.4.0-dev.20210627
- 创建main.ts
interface Point2D{
x:number,
y:number
}
interface Point3D{
x:number,
y:number,
z:number
}
var point2D:Point2D = {
x:0,
y:0
}
var point3D:Point3D = {
x:0,
y:10,
z:20
}
function iTakePoint2D(point:Point2D){
}
iTakePoint2D(point2D);
iTakePoint2D(point3D);
iTakePoint2D({
x:0
})
- 编译main.ts,
tsc main.ts
编译得到了main.js,如下,
//main.js
var point2D = {
x: 0,
y: 0
};
var point3D = {
x: 0,
y: 10,
z: 20
};
function iTakePoint2D(point) {
}
iTakePoint2D(point2D);
iTakePoint2D(point3D);
iTakePoint2D({
x: 0
});
编译时,iTakePoint2D({ x:0 })
处报错如下,
Argument of type ‘{ x: number; }’ is not assignable to parameter of type ‘Point2D’. Property ‘y’ is missing in type ‘{ x: number; }’ but required in type ‘Point2D’.ts(2345)
main.ts(3, 5): ‘y’ is declared here.
即使存在编译错误,TypeScript代码也会尽可能地被编译为JavaScript代码,也就是说,类型错误不会阻止JavaScript代码的正常运行。
示例2 ?: 可选属性
function getRandomNum(){
return Math.floor(Math.random()*100);
}
function foo(a,b){
if(getRandomNum()>50){
return {
a:1,
b:2
}
}else{
return {
a:1,
b:undefined
}
}
}
其实,我们应该尽量避免显式使用undefined
,而TypeScript又正好可以将结构和值分开,所以对以上代码进行如下改进,
function getRandomNum(){
return Math.floor(Math.random()*100);
}
function foo(a:number,b?:number){
if(getRandomNum()>50){
return {
a:1,
b:2
}
}else{
return {
a:1
}
}
}
?:
表示可选属性。
示例3 返回值类型
function toInt(str:string){
return str ? parseInt(str) : undefined;
}
改进如下,
function toInt(str:string):{valid:boolean,int?:number}{
const int = parseInt(str);
if(isNaN(int)){
return {valid:false};
}else{
return {valid:true,int};
}
}
:{valid:boolean,int?:number}
,声明函数返回值类型,其中int
是可选项。
TypeScript的工程化
先列出完整项目的目录吧,接下来我们慢慢来。
1、tsc --init 生成tsconfig.json
mkdir test
cd test
tsc --init
tsc --init
后,会在根目录test下自动生成tsconfig.json
,如下,
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
如果一个目录下存在一个tsconfig.json
文件,那么就意味着这个目录是TypesScript项目的根目录。
我们知道,TypeScript最终会编译成JavaScript文件执行,TypeScripti编译器就是根据tsconfig.json
中的配置信息对TypeScript项目进行编译。
- target,指定EMCAScript的目标版本。
- module,指定生成哪个模块系统代码。
- forceConsistentCasingInFileNames,禁止对同一个文件的不一致的引用。
在ts中,如果要引入一个通过export = foo
导出的模块,标准的语法是require("foo")
或者import * as foo from "foo"
,但是由于历史原因,我们已经习惯了使用import foo from "foo"
。
如果forceConsistentCasingInFileNames
设置为true
,才允许使用import foo from "foo"
引入通过export=foo
导出的模块;当设置forceConsistentCasingInFileNames
为false
时,则不允许,会报错。 - strict,启用所有严格类型检查选选项。
- skipLibCheck,忽略所有的声明文件(
*.d.ts
)的类型检查。
2、集成构建工具webpack
2.1、npm init -y 生成package.json
npm init -y
后,会自动生成package.json文件,如下,
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
2.2、下载安装webpack构建工具及相关插件
npm install --save-dev webpack webpack-cli html-webpack-plugin clean-webpack-plugin
2.3、下载安装TypeScript及加载器
npm install --save typescript@next
npm install --save-dev ts-loader
最后的package.json如下,
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0-alpha.0",
"html-webpack-plugin": "^5.3.2",
"ts-loader": "^9.2.3",
"webpack": "^5.41.1",
"webpack-cli": "^4.7.2"
},
"dependencies": {
"typescript": "^4.4.0-dev.20210702"
}
}
2.4、入口文件index.ts
新建目录src,在src目录下添加入口文件index.ts。
本例中需要使用第三方库big.js,所以需要下载big.js及其类型声明。
npm install --save big.js @types/big.js
// index.ts
import { Big } from "big.js";
let x:number = 0.1;
let y:number = 0.2;
let z:number = x + y;
console.log(z);
let a:Big = new Big(0.1);
let b:Big = new Big(0.2);
let c:number = Number(a.plus(b));
console.log(c);
let zEle = document.createTextNode(z.toString());
let cEle = document.createTextNode(c.toString());
document.body.appendChild(zEle);
document.body.appendChild(document.createElement("br"));
document.body.appendChild(cEle);
2.5、webpack配置文件webpack.config.js
webpack.config.js配置文件的内容如下,
// webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const { webpack } = require("webpack");
module.exports = {
mode:"development",
devtool:"source-map",
entry: "./src/index.ts",
output: {
filename: "bundle.js",
path:path.resolve(__dirname,"dist")
},
resolve: {
extensions: [ ".ts", ".tsx", ".js"]
},
module: {
rules: [
// all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
{
test: /\.tsx?$/,
use: [{
loader:"ts-loader"
}],
exclude:/node_modules/
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:"./index.html"
}),
new CleanWebpackPlugin()
]
};
项目根目录下添加了html模板,index.html,如下,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
3、npm run build,编译项目
D:\JsProjects\test>npm run build
> test@1.0.0 build D:\JsProjects\test
> webpack --config webpack.config.js
asset bundle.js 27.4 KiB [emitted] (name: main) 1 related asset
asset index.html 307 bytes [emitted]
./src/index.ts 525 bytes [built] [code generated]
./node_modules/big.js/big.js 25.2 KiB [built] [code generated]
webpack 5.41.1 compiled successfully in 1417 ms