定义typescript类方法

时间:2018-03-30 23:19:54

标签: javascript typescript

我找不到关于类方法的“声明然后初始化”的任何信息,例如我可以这样做(下面的代码),首先声明getName()然后初始化它,tslint提示我,我不能这样做,那么我应该做什么,如果不想建构,如public getName(name: string): string { return this.name }

class Cat {
  public getName(name: string): string;
  
  constructor() { ... }
  
  getName(name) {
    return this.name;
  }
}

2 个答案:

答案 0 :(得分:4)

分离"声明然后初始化"的一个原因。是有助于将公共接口与私有实现分开。

在TypeScript中,可以通过使用interface作为声明和类作为初始化来实现。此外,TypeScript内置了该语言的模块系统,因此您可以将整个类作为私有实现细节,而不是导出并且在模块外部不可用,而不是在类中公开一些内容和私有内容。

export interface Cat {
    getName(name: string): string;
}


// NOTE: this whole class is an implementation detail and is not exported
class CatImpl implements Cat {

  name: string;

  constructor() { }


  getName(name: string) {
    return this.name;
  }
}

// this is exported and is publicly available for creating Cats
export function createCat(): Cat {
    return new CatImpl();
}

答案 1 :(得分:0)

虽然我看不出你想要这样做的充分理由,但这根本不可能。