代码改变世界

TypeScript笔记(二)高级类型

2024-07-07 19:09  jiayayao  阅读(7)  评论(0编辑  收藏  举报

一、Class

class Person {
    constructor(name: string) {
        this.namee = name
        console.log(this.namee)
    }
    namee:string = '';
}
let person = new Person('Jane');

1.1 类方法

class Point {
  x: number = 0;
  y: number = 0;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
  scale(n:number):void {
    this.x *= n;
    this.y *= n;
  }
}

let p = new Point(1, 2);
p.scale(2);
console.log(p.x, p.y);

1.2 类继承

两种方式,一种是extends(继承父类,仅JS);一种是implements(实现接口,TS提供)

class Animal {
  constructor(public name: string) {}

  move(meters: number) {
    console.log(`${this.name} moved ${meters}m.`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }
  bark() {
    console.log("Woof! Woof!");
  }
}
interface sing {
    sing(): void;
}

class singer implements sing {
    sing() {
        console.log("hello world");
    }
}

类可见性:public/protected/private

protected:仅所在类和子类(不含实例对象)中可见

private:仅所在类可见

1.3 只读修饰符

readonly: 只读,防止在构造函数之外,对属性进行赋值;只能修饰属性,不能修饰方法;

class Person {
    readonly name:string;
    constructor(name:string){
        this.name = name;
    }
}

let p = new Person('Tom');
p.name = 'Jerry'; // 报错

1.4 类型兼容性

两种:1、Structural Type System(结构化类型系统)2、Nominal Type System(标明类型系统)

TS采用的是结构化类型系统,关注的是值所具有的形状。

少的参数赋值给多的参数是没有问题的,反之报错。

type F1 = (a:number) => void
type F2 = (a:number, b:number) => void

let f1:F1 = (a) => {
    console.log(a)
}
let f2:F2 = f1

 交叉类型,符号&,用于组合多个类型为一个类型。

interface sing {
    sing(): void;
}

interface dance {
    dance(): void;
}

type Person = sing & dance;

let obj:Person = {
    sing(){
        console.log("sing");
    },
    dance(){
        console.log("dance");
    }
}

交叉类型(&)和接口继承(extends)都可以实现对象类型的组合,区别在于相同名称函数的处理上,交叉类型函数的参数是或的关系,接口继承会报错;

二、泛型

泛型可以在保证类型安全的同时,一次实现多种类型的函数。(类似c++中的模版?)

function id<Type>(value:Type):Type{
    return value;
}

由于TS有类型推断机制,可以使用如下方法调用:

let test = id<number>(1);
let test2 = id(2);

2.1 泛型约束

1、指定具体的类型

function id<Type>(value:Type[]):number{
    return value.length;
}

2、extends 添加约束

3、多个泛型,泛型之间存在约束

function getProp<Type, Key extends keyof Type>(obj: Type, key: Key): Type[Key] {
  return obj[key];
}
  getProp({ a: 1, b: 2 }, "a")

keyof 接收一个对象类型,获取对象类型key的集合。

2.2 泛型接口

P56