TypeScript入门

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导出的模块;当设置forceConsistentCasingInFileNamesfalse时,则不允许,会报错。
  • 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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值