这是我参与「第四届青训营 」笔记创作活动的第14天
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版本发布
更新快,非常有活力
JavaScript:动态类型,弱类型语言
TypeScript:静态类型,弱类型语言
动态类型和静态类型区别:编译发生的时间不同
TypeScript的优势
静态类型
- 可读性增强:基于语法解析 TSDoC, IDE增强
- 可维护性增强:在编译阶段暴露大部分错误 => 多人合作的大型项目中,获得更好的稳定性和开发效率
JS的超集
- 包含于兼容所有Js特性,支持共存
- 支持渐进式引入与升级
推荐编辑器
-
Visual Studio Code
-
TypeScript官网在线编辑器
基本语法
基础数据类型
/*字符串*/
const q: string = 'string';
/*数字*/
const W: number = 1;
/*布尔值*/
const e: boolean = true;
/*null*/
const r: null = nult;
/* undefined */
const t: undefined = undefined;
对象类型
一般用大写I开头,表示这是一种类型,用来和对象还有类进行区分
interface IBytedancer {
/*只读属性:约束属性不可在对象初始化外赋值*/
readonly jobId: number ;
name: string ;
sex: 'man'| 'woman' | 'other';
age: number;
/*可选属性: 定义该属性可以不存在*/
hobby ?: string;
/*任意属性:约束所有对象属性都必须是该属性的子类型*/
[key: string]: any;
}
函数类型
function add(x: number, y: number): number {
return x + y;
}
const mult: (x: number , y: number) => number = (x, y) => x * y;
interface IMult {
(x: number, y: number) : number ;
}
const mult:
IMult=(x,y)=>X*y;
函数重载
/*对getDate函数进行重载, timestamp为可缺省参数*/
function getDate(type: 'string', timestamp?: string): string;
function getDate(type: 'date',timestamp?: string): Date;
function getDate(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
数组类型
/*「类型+方括号」表示 */
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, 6];
const arr2: IArr2 = [1, 2,'3','4',{a:1}];
const arr3: IArr3 = [1, 2,'3','4'] ;
const arr4 :IArr4 =['string', () => null, {},[]];
TypeScript补充类型
/* 空类型,表示无赋值 */
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>;
Typescript泛型
function getRepeatArr(target) {
return new Array(100).fill(target);
}
type IGetRepeatArr = (target: any) => any[] ;
/*不预先指定具体的类型,而在使用的时候再指定类型的一种特性*/
type IGetRepeatArrR = <T>(target: T) => T[] ;
/*泛型接口&多泛型*/
interface IX<T, U> {
key: T;
val: U;
}
/*泛型类 */
class IMan<T> {
instance: T ;
}
/*泛型别名 */
type ITypeArr<T> = Array<T>;