typescript学习笔记

329 阅读5分钟

1. 静态类型深度理解

const count: number = 2021;
count.toFixed(2);

count只能是一个number数据类型,并且具备number类型所有的属性和方法。

interface point {

    x: number,

    y: number,

}

const point: point = {

    x3,

    y6,

}


point.x

point变量是一个自定义的静态类型,point这个变量上具备point类型所有的属性和方法!

2. 基础类型和对象类型

基础类型 null,undefined symbol(ES6 引入了一种新的原始数据类型 Symbol ,表示独一无二的值,最大的用法是用来定义对象的唯一属性名。) boolean void


const user: {

  name: string,

  age: number

} = {

    name: '狗大户',

    age: 18

}//对象类型

const nums: number [] = [1,2,3] //数组类型

class doge {}

const dell:doge = new doge()//类类型

const getDoge: () => number = () => {

    return 1+2;

}//函数类型`

3. 类型推断和类型注释

ts能够自动分析变量类型时候,我们什么也不需要做! 例:

let names = '狗大户';

let sex = '男'

let type = '有钱'

const hi = names + sex + type

ts无法分析变量类型时,我们需要使用类型注解! 例:

function getType (names: string,sex :string) {
  return names +sex
}

const hi = getType('狗大户','男')

4. 函数相关类型

// 约定返回值类型【实战中使用场景比较多】
function add(num1: number, num2: number):number {
    return num1 + num2
}
const total = add(1,2)

// 约定没有返回值 【void(空)返回值类型】
function sayHi():void {
  console.log(1)
}

//约定永远不能执行完的函数类型 【never】
function error():never {
  while(true) {}
}

//解构函数参数约定
function newAdd({num1,num2}:{num1:number,num2:number}):number {
    return num1 + num2
}
const total = newAdd({num1:1,num2:2})

箭头函数特殊返回形式 【形参为字符,返回为number类型】
const fun1:(str:string) => number = (str) => {
    return parseInt(str,5)
}

//多种静态数据类型
let temp: string | number = 123;

4. 数组与元组

数组

//num 是个数组,数组内容是number类型
const num: number[] = [1,2,3];
//newNum 是个数组,数组内容可以是number类型也可以是string类型
const newNum: (number|string)[] = ['1',2];
//对象类型数组 数组内容可以是对象,只包含字符类型name和age数字类型值
const objNum: {name: string, age: number}[] = [{
    name'狗大户'age38
}]
//type alias //类型别名
type objNumType = {name: string, age: number}
const newObjNum: objNumType[] = [{name'狗大户1'age37}]
// ts不会强行要求数组里的每一项都是 new obj实例
class objGouDaHu {
  name: string;
  age: number
}
const newGouDaHuObj:objGouDaHu[] = [
    {
        name'狗大户1',
        age38
    }
]


元组

// 普通元组-【元组: **数量,个数,数据类型有限的数组**】
const teacher: [string,string,number] = ['狗大户','有钱',70]
//复杂元组类型-(带小括号)
const list:([string,boolean,number])[] = [['大佬',false,35],['菜鸡',true,25],['混子',false,.30]]
//复杂元组类型
const newList:[string,boolean,number][] = [['大佬',false,35],['菜鸡',true,25],['混子',false,.30]]

5. interface接口

interface 接口 (interface 和 type相类似,但并不完全一致)

interface Person {
    name: string;
    age?: number; //age属性可有可无
    readonly type: string; //属性只能读不能写
    [proName: string]: any; //Person可以有其他属性
    say(): string; //Person存方法
}
const getPerson = (person:Person)=> {
  console.log(person,'person')
}
const data = {
  name'狗大户',
  age45,
  type'有钱',
  sex'男',
  say() {
    return '真主阿拉!'
  }
}
getPerson(data)

//interface 接口继承(newPerson继承了Person的类型并拥有自己的新类型)
interface newPerson extends Person {
    newPersons(): string
}
const newGetPerson = (newPerson: newPerson) => {
    console.log(newPerson)
}
const newData = {
    name'狗大户',
    age45,
    type'有钱',
    sex'男',
    say() {
        return '真主阿拉!'
    },
    newPersons() {
        return '白嫖可耻!'
    }
}
newGetPerson(newData)

//interface 函数类型(定义函数类型声明,接收一个string类型,返回一个string类型)
interface sayHi {
    (word: string): string
}
const sayHi: sayHi = (word: string) => {
    return '123'
}

6. ts类的定义与继承

class You {
  type: string = '暴富';
  getYou () { return this.type}
}
//继承
class Me extends You {
  getMe() { return '帅气逼人~'}
  getYou () { 
      //super指向父类 (当一个类把父类方法重写时,可以使用super去调用父类的方法~)
      return super.getYou() + '超级健康~';
  }
}
const me = new Me();

7. ts类中的访问类型和构造器。(构造器:本质上是对类的构造进行,包装,修改。)

1.public 允许我在类的外部使用
class Person {
  public name: string = 'you';
  public sayHi () {
    this.name;
    console.log("hi!")
  }
}
const dalao = new Person();
dalao.name = 'who?' //因为name是public声明的,所以我们可以在外部使用它~

2.private 允许在类内使用~
class Person {
  private name: string = 'you';
  public sayHi () {
    this.name = '狗蛋~'; //因为name是private声明的,所以在类的外部我们不可以调用name属性~
    console.log("hi!"+this.name)
  }
}
const dalao = new Person();
dalao.sayHi()

3.protected 允许在类内及继承的子类中使用
class Person {
  protected name: string = 'you';
  public sayHi () {
    this.name = '狗蛋~';
    console.log("hi!"+this.name)
  }
}
class newPerson extends Person {
  sayBye () {
    this.name = '二狗子~' //因为我是protected声明的。所以我变成了二狗子~
    console.log('hi'+this.name)
  }
}
const dalao = new newPerson();
dalao.sayBye()

构造器 constructor

class newPay {
  public type: string = '微信';
  constructor(type:string) {
    this.type = type
  }
} // newPay的简写(Pay)

class Pay {
  constructor (public type:string) {}
}// 等同于 newPay

//当子类继承父类时,子类需要声明构造器时必须调用父类构造器,并传递必传参数(super)
class Pays extends Pay {
  constructor(public num:number) {
    super('京东支付')
  }
}

8. 静态属性,Setter和Getter

class Person {
    constructor (private name: string) {}
    get getName() {
        return this.name
    }
    set getName(newName: string) {
        const realName = newName.split(',')[0]
        this.name = realName
    }
}
//Setter和Getter的作用在于治理(比如说,我的密码,不能给你,但你我可以把加密后的一段密码给你,中间做个转化!)

const person = new Person('hi');
console.log(person.getName//这是getter的一个写法,不需要你person.getName()

person.getName = 'hi,二狗子!'

//单例模式(这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。)
class Dome {
    private static instanceDome;
    private constructor(public name:string) {}
    static getInstance() {
        //static 是指把方法直接挂在类上,而不是类的实例上!
        if (this.instance) {
            this.instance = new Dome('我是一个单例模式')
        }
        return this.instance;
    }
}
const Dome1 = Dome.getInstance()
const Dome2 = Dome.getInstance()
console.log(Dome1 === Dome2)

9.抽象类

abstract class Geom {
  abstract getArea():number //如果给类的方法加了abstract,意味着这个类的方法也是抽象的!
}
//抽象类只能被继承不能被实例化~
class Circle extends Geom {
  getArea () {
    return 123
  }
} //子类继承的,父类中有抽象的,方法,你必须把它实现出来!