Skip to content

Typescript 泛型与类 ​

一、泛型 ​

泛型相当于类型变量,在使用时确定具体类型。

基本使用 ​

ts
const getArray = <T>(value: T, times: number = 5): T[] => {
  return new Array(times).fill(value)
}
getArray<number>(123, 4)
const getArray = <T>(value: T, times: number = 5): T[] => {
  return new Array(times).fill(value)
}
getArray<number>(123, 4)

多个泛型 ​

ts
const getArray = <T, U>(value: T, params: U, times: number): Array<[T, U]> => {
  return new Array(times).fill([value, params])
}
getArray(1, 'a', 3)
const getArray = <T, U>(value: T, params: U, times: number): Array<[T, U]> => {
  return new Array(times).fill([value, params])
}
getArray(1, 'a', 3)

接口中使用泛型 ​

ts
// 方式一:调用时指定
interface GetArr {
  <T>(arg1: T, times: number): T[]
}

// 方式二:定义时指定
interface GetArr<T> {
  (arg1: T, times: number): T[]
  array: T[]
}
// 方式一:调用时指定
interface GetArr {
  <T>(arg1: T, times: number): T[]
}

// 方式二:定义时指定
interface GetArr<T> {
  (arg1: T, times: number): T[]
  array: T[]
}

泛型约束 ​

ts
// extends 约束必须有 length 属性
interface ValueWithLength {
  length: number
}
const getArr = <T extends ValueWithLength>(arg1: T, times: number): T[] => {
  return new Array(times).fill(arg1)
}
getArr(123)  // 报错,number 没有 length

// extends keyof 约束为对象的键
const getProps = <T, K extends keyof T>(object: T, propName: K): T[K] => {
  return object[propName]
}
getProps({ a: 'a', b: 'b' }, 'c')  // 报错
// extends 约束必须有 length 属性
interface ValueWithLength {
  length: number
}
const getArr = <T extends ValueWithLength>(arg1: T, times: number): T[] => {
  return new Array(times).fill(arg1)
}
getArr(123)  // 报错,number 没有 length

// extends keyof 约束为对象的键
const getProps = <T, K extends keyof T>(object: T, propName: K): T[K] => {
  return object[propName]
}
getProps({ a: 'a', b: 'b' }, 'c')  // 报错

默认值 ​

ts
function createArr<T = string>(params: T): Array<T> {
  return new Array(params)
}
function createArr<T = string>(params: T): Array<T> {
  return new Array(params)
}

二、类 ​

定义类 ​

ts
class Point {
  public x: number
  public y: number
  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
  public getPosition() {
    return `(${this.x}, ${this.y})`
  }
}
class Point {
  public x: number
  public y: number
  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
  public getPosition() {
    return `(${this.x}, ${this.y})`
  }
}

修饰符 ​

修饰符作用
public公开(默认)
private私有,仅类内部访问,继承也不能访问
protected受保护,仅类内部和子类可访问,不能实例化
readonly只读
static静态属性/方法,通过类名访问
ts
class Parent {
  public name: string
  private age: number        // 私有
  protected sex: string      // 受保护
  public readonly id: string // 只读
  public static count = 0    // 静态

  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
}
console.log(Parent.count)  // 静态属性
class Parent {
  public name: string
  private age: number        // 私有
  protected sex: string      // 受保护
  public readonly id: string // 只读
  public static count = 0    // 静态

  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
}
console.log(Parent.count)  // 静态属性

私有字段(TS 3.8+) ​

ts
class Person {
  private name: string       // 可通过 Person['name'] 访问
  #name: string              // 不能通过 Person['#name'] 访问
}
class Person {
  private name: string       // 可通过 Person['name'] 访问
  #name: string              // 不能通过 Person['#name'] 访问
}

参数属性 ​

简化属性初始化的写法:

ts
class A {
  constructor(public name: string) {}
}
// 等价于
class A {
  public name: string
  constructor(name: string) {
    this.name = name
  }
}
class A {
  constructor(public name: string) {}
}
// 等价于
class A {
  public name: string
  constructor(name: string) {
    this.name = name
  }
}

存取器 ​

ts
class Info {
  private _info: string = ''
  get infoStr() {
    return this._info
  }
  set infoStr(val: string) {
    this._info = val
  }
}
class Info {
  private _info: string = ''
  get infoStr() {
    return this._info
  }
  set infoStr(val: string) {
    this._info = val
  }
}

抽象类 ​

只能继承,不能直接实例化:

ts
abstract class People {
  constructor(public name: string) {}
  public abstract printName(): void
}
class Man extends People {
  constructor(name: string) {
    super(name)
  }
  public printName() {
    console.log('Man')
  }
}
abstract class People {
  constructor(public name: string) {}
  public abstract printName(): void
}
class Man extends People {
  constructor(name: string) {
    super(name)
  }
  public printName() {
    console.log('Man')
  }
}

类实现接口 ​

ts
interface Food {
  type: string
}
class Fool implements Food {
  public type: string = 'fruit'
}
interface Food {
  type: string
}
class Fool implements Food {
  public type: string = 'fruit'
}

接口继承类 ​

ts
class A {
  protected name: string
}
interface I extends A {}
class B extends A implements I {
  public name: string
}
class A {
  protected name: string
}
interface I extends A {}
class B extends A implements I {
  public name: string
}

泛型中使用类类型 ​

ts
const create = <T>(c: new () => T): T => {
  return new c()
}
class Info {
  public name: string = 'h'
}
create(Info)
const create = <T>(c: new () => T): T => {
  return new c()
}
class Info {
  public name: string = 'h'
}
create(Info)