day4 TypeScript 入门 | 青训营笔记

73 阅读4分钟

这是我参与「第五届青训营 」笔记创作活动的第4天

day4 TypeScript 的发展与基本语法

一、TypeScript发展历史

  • 2012-10:微软发布了TypeScript第一个版本(0.8)

  • 2014-10: Angular 发布了基于TypeScript的2.0版本

  • 2015- -04:微软发布了Visual Studio Code

  • 2016- -05: @types/react 发布,TypeScript 可开发React

  • 2020-09: Vue 发布了3.0 版本,官方支持TypeScript

  • 2021-11: v4. 5版本发布

    TS源于JS, JS是动态类型,TS是静态类型,他们都是弱类型语言

静态类型可读性增强:基于语法解析TSDoc, ide增强
可维护性增强:在编译阶段暴露大部分错误;多人合作的大型项目中,获得更好的稳定性和开发效率
JS的超集●包含于兼容所有Js特性,支持共存●支持渐进式引入与升级

二、基本语法

基础数据类型

/* 字符串 */
const q: string = 'string';
/* 数字 */
const w: number = 1;
/* 布尔值 */
const e: boolean = true;
/* null */
const r: null = null;
/* undefined */
const t: undefined = undefined;

对象类型

在ts编写约定中会用大写的I开头表示这是一个类型用于和我们的对象和普通的类区分

image-20230119213556808.png

函数类型

声明类型有两种方式:1、直接在函数上补充类型声明2、给函数变量赋值一个函数类型声明

image-20230119214427137.png

数组类型

/*「类型+方括号」表示*/
type IArrl = 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, 6];
const arr2: IArr2 = [1, 2, '3''4', { a: 1 }];
const arr3: IArr3 = [1, 2, '3', '4'];
const arr4: IArr4 = ['string', () => null, {}, []];

TS补充类型

/*空类型,表示无赋值*/
type IEmptyFunction = () => void;
/*任意类型,是所有类型的子类型*/
type IAnyType = any;
/*枚举类型:支持枚举值到枚举名的正、反向映射*/
enum EnumExample {
add="+"
mult="*"
}
EnumExample['add'] === '+';
EnumExample['+'] === 'add ';
enum ECorlor { Mon, Tue, Wed, Thu, Fri, Sat, Sun };
ECorlor['Mon'] === 0;
ECorlor[0] === 'Mon' ;
/*泛型*/
type INumArr = Array<number>;

字符串/数字 字面量

且或语法

/*允许指定字符串/数字必须的固定值 */
/* IDomTag必须为html、 body、 div、span中的其一*/
type IDomTag = 'html' | ' body' | 'div' | ' span';
/* IOddNumbe r必须为1、3、5、7、9中的其一*/
type IOddNumber=1|3|5|7|9;

高级类型

联合/交叉类型

为书籍列表编写类型

const bookList = [{
    author:'xiaoming' ,
    type: 'history',
    range: '2001-2021'
},{
    author:'xiaoli',
    type:'story', 
    theme: 'love',
}]

类型声明繁琐,存在较多重复

interface IHistoryBook {
    author: string ;
    type: string;
    range: string 
}
interface IStoryBook {
    author: string;
    type: string ;
    theme: string;
}
type IBookList = Array<IHistoryBook| IStoryBook> ;
  • 联合类型: IA | IB;联合类型表示一个值可以是几种类型之一
  • 交叉类型: |IA & IB;多种类型叠加到一起成为一种类型, 它包含了所需的所有类型的特性
type IBookList = Array<{
	author: string;
}&({
    type: 'history';
    range: string;
}|{
    type:'story';
    theme: string;
})>

类型保护与类型守护

只能访问联合类型的公共交集

interface IA { a: 1, al: 2 }
interface IB { b: 1, b1: 2 }
function log(arg: IA| IB) {
/*报错:类型“IA 1IB”上不存在属性"a”。 类型“1B"上不存在属性"a”。 */
/*结论:访问联合类型时,处于程序安全,仅能访问联合类型中的交集部分*/
    if (arg.a) {
    	console.log(arg.a1)
    } else {
		console.log(arg.b1);
     }
}

改进

/*类型守卫定义一个函数,它的返回值是一个类型谓词 ,生效范围为子作用域*/
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);
    }
} 

联合类型 + 类型保护 = 自动类型推断

function logBook(book:IBookItem) {
  if(book.type == 'history') {
    console.log(book.range)
  } else {
    console.log(book.theme)
  }
}

高级类型

/**
实现merge函数类型
要求sourceObj必须为targetObj的子集
*/
function merge1(source0bj, target0bj) { 
    const result = { ..source0bj };
    for(let key in target0bj) {
        const itemVal = source0bj [key];
        itemVal &&s ( result[key] = itemVal );
    }
	return result;
}
function merge2(source0bj, target0bj) {
	return { ... source0bj, ... target0bj };
}

函数返回值类型

//1实现函数delayCall的类型声明
// delayCal接受个函数作为入参, 其实现延迟1s运行函数
//其返回promise,结果为入参函数的返回结果
function delayCall(func) {
    return new Promise( resolve => {
        setTimeout(() => {
            const result = func();
            resolve( result);
        }, 1000);
    });
}

还是使用泛型

  • 关键字[extends]跟随泛型出现时,表示类型推断,其表达可类比三元表达式
  • 如T===判断类型?类型A:类型B
  • 关键字[infer] 出现在类型推荐中,表示定义类型变量,可以用于指代类型
  • 如该场景下,将函数的返回值类型作为变量,使用新泛型R表示,使用在类型推荐命中的结果中
type IDelayCall = <T extends () => any>(func: T) => ReturnType<T>; 
type IReturnType<T extends (...args: any) => any> = T extends (...args: any)
=>inferR?R:any

四、工程应用

主要是浏览器Web|Node.js 两种实现方式相似

webpack

  1. 配置webapack loader相关配置

  2. 运行webpack启动/ 打包

  3. 配置tsconfg.js文件

  4. loader处理ts文件时, 会进行编译与类型检查

node.js

使用TSC编译

image-20230119222936752.png

  1. 安装Node与npm
  2. 使用npm安装tsc
  3. 配置tsconfhg.js文件
  4. 使用tsc运行编译得到js文件