Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 清理TypeScript中类构造函数的方法?_Javascript_Typescript_Class - Fatal编程技术网

Javascript 清理TypeScript中类构造函数的方法?

Javascript 清理TypeScript中类构造函数的方法?,javascript,typescript,class,Javascript,Typescript,Class,目前,我用以下方式定义我的类构造函数 class MyClass { routerStore: RouterStore characterStore: CharacterStore characterPrivateStore: CharacterPrivateStore constructor( routerStore: RouterStore, characterStore: CharacterStore, characterPrivateStore

目前,我用以下方式定义我的类构造函数

class MyClass {

  routerStore: RouterStore
  characterStore: CharacterStore
  characterPrivateStore: CharacterPrivateStore

  constructor(
    routerStore: RouterStore,
    characterStore: CharacterStore,
    characterPrivateStore: CharacterPrivateStore
  ) {
    super()
    this.routerStore = routerStore
    this.characterStore = characterStore
    this.characterPrivateStore = characterPrivateStore
  }
}

这让我觉得冗长和重复。鉴于TypeScript利用了一些最新的JavaScript建议,我想问一下,是否有可能以某种方式清理这个问题?

您可以向constructorparameter添加一个访问修饰符。这将使参数也成为一个类字段,该类字段将使用参数的值进行初始化

class MyClass {


   constructor(
       public routerStore: RouterStore,
       public characterStore: CharacterStore,
       public characterPrivateStore: CharacterPrivateStore
    ) {
       super()
   }
}
您还可以使用
Object.assign
声明类上的字段,并使用映射类型仅提取字段键(排除方法):

type JustFieldKeys={[P in keyof T]:T[P]扩展函数?never:P}[keyof T]
类MyClass{
公共路由器商店!:路由器商店,
公共字符库!:字符库,
public characterPrivateStore!:characterPrivateStore
构造函数(参数:Pick){
Object.assign(此参数);
}
}
新MyClass({
characterPrivateStore:null,
characterStore:null,
路由器存储:空
})

整洁。我使用的是microsoft tslint预设,它尖叫着
[tslint]属性“routerStore”无法在构造函数中声明(无参数属性)
这是我的。在将public添加到构造函数参数时,有什么特别的原因会发出警告吗?@Ilja列出的理由是:参数属性可能会让TS新手感到困惑,因为它们没有其他声明和初始化类成员的方法那么明确。这似乎不是禁止使用该功能的一个很好的理由。
type JustFieldKeys<T> = { [P in keyof T] : T[P] extends Function ? never : P }[keyof T] 
class MyClass {

    public routerStore!: RouterStore,
    public characterStore!: CharacterStore,
    public characterPrivateStore!: CharacterPrivateStore
    constructor(params: Pick<MyClass, JustFieldKeys<MyClass>>) {
        Object.assign(this, params);
    }
}
new MyClass({
    characterPrivateStore: null,
    characterStore: null,
    routerStore: null
})