TypeScript基本介绍

前言

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

这里有一个本身用TypeScirpt编写的工具库,欢迎你们使用和互相学习,有时间会写下文章讲下如何开发和发布本身的工具库。git

什么是TypeScript

TypeScript是Javascript的超集,并添加可选的静态类型和类别,但浏览器没法识别,因此要经过工具转换为Javascript代码才能够在浏览器上运行。github

为何要用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');  // 报错,由于上面以指定数组为数字类型
复制代码
相关文章
相关标签/搜索