TypeScript 的发展与基本语法| 青训营笔记

49 阅读2分钟

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

什么是 TypeScript

  • TypeScript是微软开发的一个开源的编程语言,通过在JavaScript的基础上添加静态类型定义构建而成。

  • TypeScript通过TypeScript编译器或Babel转译为JavaScript代码,可运行在任何浏览器,任何操作系统。

类型分类:

  • 基础数据类型
  • 对象类型
  • 函数类型
  • 函数重载
  • 数据类型
  • 补充类型
  • 联合交叉类型
  • 类型保护与类型守卫
  • 函数返回值类型

基本语法

/* 字符串 */ 
const a: string = 'string'; 
/* 数字 */ 
const a: number = 1; 
/* 布尔值 */ 
const a: boolean = true;
/* null */ 
const a: null = null; 
/* nudefined */ 
const a: nudefined = nudefined;

对象类型:

const bytedancer: IBytedancer = {
    jobId:9303254,
    name: 'thr',
    sex: 'man',
    age: 20,
    hobby: 'TS',
}

interface IBytedancer {
    /*只读属性:不能修改对象初始化的值*/
    readonly jobId: number;
    name: string;
    sex: 'man' | 'woman' | 'other';
    age: number;
    /* 可选属性:定义该属性可以不存在*/
    boddy?: string;
    /*任意属性:所有对象属性都必须是该属性的子类型*/
    [key: string]: any;
}
/*报错:无法分配到jobId,它是只读属性*/
bytedancer.jobId= 12345;
/*成功:任意属性标注下可以添加任意属性*/
bytedancer.plateform= 'data';
/*报错:缺少属性'name',hobby可以缺省*/
const bytedancer2: IBytedancer = {
    jobId:56478,
    sex: 'woman',
    age: 18,
}

函数类型:

/* 直接定义函数 */
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; 

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


function add(x: number, y: number): number {
    return x + y;
}
const mult: (x: number, y: number) => number = (x, y) => x * y;

数组类型

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, {}, []];

其他类型

  • 空类型,表示无赋值;
  • 任意类型,所有类型的子类型;
  • 枚举类型,支持枚举值到枚举名的正反向映射;
type IEmptyFunction = () => void;

type IAnyType = any;

enum EnumExample {
    add = '+',
    mult = '*',
}
EnumExample['add'] === '+';
EnumExample['+'] === 'add';

泛型:

  • extend 声明表示泛型必须限制在某一范围内;
  • 指定泛型默认类型;
function getRepeatArr(target) {
    return new Array(100).fill(target);
}
/*不预先指定具体的类型,而在使用的时候再指定类型的一种特性*/
type IGetRepeatArrR = <T>(target: T) => T[];
/*泛型接口&多泛型*/
interface IX<T, U> {
    key: T;
    val: U;
}
/*泛型类*/
class IMan<T> {
    instance: T;
}
/*泛型别名*/
type ITypeArr<T> =Array<T>;

断言

let a: any = [1, 2, 3];
let b: number = (a as number[]).reduce(v => v);

字符串/数字 字面量

type IDomTag = "html" | "body" | "div";
type IOddNumber = 1 | 2 | 3 | 4 | 5 | 6 ;