这是我参与「第四届青训营 」笔记创作活动的第12天
TypeScript入门
TypeScript简介
TypeScript是JavaScript的超集,扩展了JavaScript的语法,包含于兼容所有JavaScript特征,因此可与JavaScript共存。并支持渐进式引入与升级。
TypeScript的优点
静态输入
TypeScript可以在编译脚本时检测错误,查找并修复错误,从而编写更优质的代码并对其进行维护,一边是的代码更好,更清晰。
大型的开发项目
当需要改进开发项目时,需要对代码库进行小的更改。使用TypeScript工具可以对开发项目的重构变得更容易、更快。
更好地协作
当开发大型项目时,开发中的错误也会增加。类型安全是一种在编码期间检测错误的功能,而不是在编译项目时检测错误。
基本语法
基础数据类型
/*字符串*/
const s: string = 'string';
/*数字*/
const n: number = 1;
/*布尔*/
const b: boolean = true;
/*null*/
const n: null = null;
/*undefined*/
const u: undefined = undefined;
与JavaScript不同的是:TypeScript在定义变量时,在变量名后跟个冒号 :,毛猴后便是变量类型
对象类型
interface IClass{
readonly Id: number;//只读属性,不可在对象初始化外赋值
name: string;
sex: 'man' | 'woman';
age: number;
hobby?:string;//可选属性,该属性可有可无
[key:string]:any;//任意属性:约束所有对象必须都是该属性的子类型
}
//定义对象
const ClassName: IClass{
Id: 1
name: tushao
sex: man
age: 22
hobby: 'basketball'
}
函数类型
普通函数:
function add(x: number/*入口参数类型*/,y: number):number/*函数返回值类型*/{
return x + y;
}
箭头函数:
const mult:(x: number/*入口参数类型*/,y: number) => number/*函数返回值类型*/ = (x, y) => x * y;
使用interface关键字:
interface IName{
(x: number/*入口参数类型*/, y: number): number/*函数返回值类型*/;
}
const mult: IName = (x, y) => x * y;
函数重载
function getDate(type: 'string',timestamp?: string): string;
function getDate(type: 'date',timestamp?: string): Date;
function getData(type:'string' | 'date',timestamp:? string):Date | string{
const date = new Date(timestamp);
return type === 'string' ? date.toLocaleString() : date;
}
const x = getDate('date');//x: Date
const y = getDate('string', '2018-01-10');//y: string
当第一个参数是date,返回值为Date类型;当第一个参数是string,返回值为string类型。第二个参数为缺省参数,可传可不传。
数组类型
//类型[]
type IArr1 = number[];
//泛型表示
type IArr2 = Array<string | number | Record<string,number>>;
//元组表示
type IArr3 = [number,number,string, string];
//接口表示
interface IArr4 {
[key: number]:any;
}
const arr1: IArr1 = [1,2,3,4,5];
const arr2: IArr2 = [1,2,'3','4',{a: 1}];
const arr3: IArr3 = [1,2,'3','4'];
const arr4: IArr4 = ['string',() => null, {},[]];
补充类型
- 通过
type关键字定义其他类型
//空类型,表示无赋值
type IEmptyFunction = () => void;
//任意类型,是所有类型的子类型
type IAnyType = any;
- 枚举类型,使用
enum关键字
enum EnumExample {
add = '+',
mult = '*',
}
EnumExample['add'] === '+';
EnumExample['mult'] === '*';
enum ECorlor {Mon,Tue,Wed,Thu,Fir,Sat,Sun};
ECorlor['Mon'] === 0;
ECorlor[0] === 'Mon';
泛型
不预先指定具体的类型,而在使用的时候再指定类型的一种特征。
//泛型函数
type IGetRepeatArrR = <T>(target:T) => T[];
//泛型接口
interface IX<T,U>{
key:T;
val:U;
}
//泛型类
class IMan<T>{
instance: T;
}
//泛型别名
type ITypeArr<T> = Array<T>;
- 泛型约束:限制泛型必须符合给定的类型
type IString = <T extends string>(target:T) => T[];
const getStr: IString = target => new Array(100).fill(target);
getStr(123)//报错:参数收到限制,必须是string类型
- 泛型参数默认类型
type IArr<T = number> = (target:T) => T[];
const getArr: IArr = target => new Array(100).fill(target);
getArr('123')//报错:定义函数时没有传泛型,默认是number
字符串/数字字面量
允许指定字符串/数字必须固定的值
type IString = '1' | '2' | '3';//必须是'1','2','3'中的其中一种
type INumber = 1 | 2 | 3;//必须是1,2,3中的其中一种
高级类型
联合/交叉类型
type IBookList = Arrar<{
author: string;
} & ({
type: 'history';
range:string;
} | {
type: 'story';
theme:string;
})>
&:多种类型的合集;|:多种类型里的其中一个。
类型保护与类型守卫
interface IA {a: 1, a1: 2}
interface IB {b: 1, b1: 2}
function log(arg: IA | IB){
if(arg.a){
console.log(arg.a1)
}else{
console.log(arg.b1)
}
}
报错:类型“IA | IB”上不存在属性‘a’。访问联合类型时,只能访问联合类型上的交集部分。
改造:
interface IA {a: 1, a1: 2}
interface IB {b: 1, b1: 2}
//类型守卫:定义一个函数,它的返回值是一个类型谓词,生效范围为子作用域
function getIsIA(arg: IA | IB): arg is IA{
return !!(arg as IA).a;
}
function log2(arg:IA | IB){
if(getIsIA(arg)){
console.log(arg.a1)
}else{
console.log(arg.b1)
}
}
工程应用
TypeScript开发环境搭建:
- 使用
npm(Node.js包管理工具) 安装TypeScript
npm install -g typescript
安装完成后通过以下方式查看版本
tsc -v
编译文件
tsc demo.ts
编译完成后生成一个js文件,可以使用node对js文件进行解析。
node demo.js
- 安装
Visual Studio的TypeScript插件
使用webpack进行打包
配置tsconfig.json文件
重要字段:
files:设置要编译的文件的名称;include:设置需要进行编译的文件,支持路径模式匹配;exclude:设置无需进行编译的文件,支持路径模式匹配;compilerOptions:设置与编译流程相关的选项。
小白创作,如有错误望指出。