Typescript

TypeScript学习笔记(二)- 类、泛型

2021-04-26  本文已影响0人  景阳冈大虫在此

有两部分:静态部分实例部分

基本

class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return this.greeting;
  }
}
class Greeter {
  name:string='dog';
}
  1. 没有修饰符、protected、private成员挂在实例上;
  2. 方法挂在类的prototype上;
  3. static修饰符挂在类上;

继承与修饰符

public:

private

protected:

readonly

static

抽象类

abstract class Talk {
  protected name: string = 'geo';
  protected constructor(str?: string) {
    // this.name = str;
  }
  abstract speaking(): void;
}
多态
abstract class Animal {
  abstract makeSound(): void;
  move(): void {
    console.log('move')
  }
}

class Dog extends Animal {
  makeSound() {
    console.log('dog makeSound');
  }
}
let dog = new Dog();

class Cat extends Animal {
  makeSound() {
    console.log('cat makeSound');
  }
}
let cat = new Cat();

let animal: Array<Animal> = [dog, cat];
animal.forEach(element => {
  console.log(element.makeSound());
});
链式调用在多态中应用
class Task{
  step1() {
    return this;
  }
  step2() {
    return this;
  }
}

new Task().step1().step2()
class Task{
  step1() {
    return this;
  }
  step2() {
    return this;
  }
}

class Story extends Task{
  next() {
    return this;
  }
}
new Story().next().step1().next().step2()

接口

interface Human {
  walk(): void;
}

interface Man extends Human {
  speak(): string;
}

interface Child extends Human {
  cry(): string;
}

class Boy implements Man, Child {
  cry(): string {
    return "";
  }

  walk() {
    return;
  }

  speak() {
    return "";
  }
}

class Control {
  state = 1;
}

interface Port extends Control {

}

class Task implements Port {
  state: number;
}

new Task();

泛型

泛型类型

function identify<T>(arg: T): T {
  return arg;
}
identify<string[]>(['a', 'b']); // 设定T类型,调用
identify(['a', 'b']);// 自动推导出T类型,调用

// 定义类型
type Log = <T>(value: T) => T;

// interface 1
interface Log {
  <T>(value: T): T
}
// interface 2
interface Log<T = string> {
  (value: T): T
}
// 调用
let log: Log<number> = identify;
console.log(identify(2));

泛型类

class Log<T>{
  run(value: T) {
    return value;
  }
}

let log1 = new Log<number>();
log1.run(1);

泛型约束

interface Length {
  length: number;
}

function logLength<T extends Length>(params: T) {
  return params.length;
}

logLength([1]);

// 类型参数
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

上一篇 下一篇

猜你喜欢

热点阅读