TypeScript入门(上)

101 阅读3分钟

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

为什么是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版本发布

为什么选择TypeScript

JSTS
动态类型静态类型
弱类型语言弱类型语言

静态类型:

  • 可读性增强:基于语法解析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;
    复制代码
    

对象类型

用大写I开头表示类型,用以与对象和类进行区分。

对象初始化:

const bytedancer: IBytedancer = {
	jobId: 9303245,
	name: 'Lin',
	sex: 'man',
	age: 28,
	hobby: 'swimming',
}
复制代码

类型定义:

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声明类型:

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 = get('string', '2018-01-10'); // y: string
复制代码

interface声明类型:

interface IGetDate {
	(type: 'string', timestamp?: string): string;
	(type: 'date', timestamp?: string): Date;
	(type: 'string'|'date', timestamp?: string): Date|string;
}

const getDate2: IGetDate = (type, timestamp) => {
	const date = new Date(timestamp);
	return type === 'string' ? date.toLocaleString() : date;
}
复制代码
  • 不能将类型(type: any, timestamp: any) => string|Date分配给类型IGetDate
  • 不能将类型string|Date分配给类型string
  • 不能将类型Date分配给类型。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];
cosnt arr2: IArr2 = [1, 2, '3', '4', {a: 1}];
const arr3: IArr3 = [1, 2, '3', '4'];
const arr4: IArr4 = ['string', () => null, {}, []];
复制代码

TypeScript基本语法就暂时介绍到这里,下篇文章将继续介绍TypeScript的补充类型和高级类型。