TypeScript基本介绍

776 阅读2分钟

前言

本文主要介绍TypeScript的基本知识,想深入了解还得去看官方文档

这里有一个自己用TypeScirpt编写的工具库,欢迎大家使用和互相学习,有时间会写下文章讲下如何开发和发布自己的工具库。

什么是TypeScript

TypeScript是Javascript的超集,并添加可选的静态类型和类别,但浏览器无法识别,所以要通过工具转换为Javascript代码才可以在浏览器上运行。

为什么要用TypeScript

使用TypeScript可以更好地编写和维护代码,因为它可以指定变量的类型,更容易知道这个变量是什么类型和拥有什么属性,并且它在编译阶段就会检查出错误,提早发现错误的时间,并且很多编辑器对TypeScript有很好的支持,会有代码提示,提高开发效率。

基础类型

  • boolean
  • number
  • string
  • Array
let nums: number[] = [1, 2, 3];
let strings: Array<string> = ['str'];
  • enum
enum Color {Red, Green, Blue}  // Color = [0, 1, 2];
let c: Color = Color.Green;  // 1
  • any
  • void
  • nullundefined
  • never

接口

对象类型

interface Shape {
  readonly type: string;  // 只读属性
  color?: string;  // 可选属性
  area: number;
  setColor(color: string): void;
  [prop: string]: any;  // 其他属性
}

函数类型

interface createShape {
    (square: Shape): Shape;
}

类类型与继承接口

interface Square extends Shape {  // 继承于Shape接口
  width: number;
  height: number;
  [prop: string]: any;  // 其他属性
}

interface ShapeConstructor {  // 构造器函数结构
  new(shape: Shape): Shape;
}

interface CircleInterface extends Shape {
  radius: number;
}

class Shape implements Shape {  // 产生Shape类型的类
  readonly type = 'shape';  // 只读属性只能在初始化时赋值
  color?: string;
  area: number;
  
  constructor(shape: Shape) {
    this.color = shape.color;
  }
  setColor(color: string) {
    this.color = color;
  }
}

class Square extends Shape implements Square {
  readonly type = 'square';  // 只读属性只能在初始化时赋值
  width: number;
  height: number;

  constructor(square: Square) {
    super(square);

    this.width = square.width;
    this.height = square.height;
    this.area = square.width * square.height;
  }
}

class Circle extends Shape implements CircleInterface {
  readonly type = 'circle';
  radius: number;
}

function createNewShape(ctor: ShapeConstructor, shape: Shape): Shape {
  return new ctor(shape);
}

泛型

泛型允许我们可以灵活地在调用期间才指定类型或由TS推断类型。

function createArray<T> (): ()=> T[] {
    return ()=> [];
}

const createNumberArray = createArray<number>();
const numberArray = createNumberArray();

numberArray.push(1);
numberArray.push('1');  // 报错,因为上面以指定数组为数字类型