如何将类导出为只读但启用内部修改?

时间:2019-11-12 07:39:09

标签: typescript

由于我的课程有异步初始化过程。我必须定义一个属性readonly public,但是在内部像

那样修改它
declare function asyncAppMap(target: string): Promise<Window>

class FrameInternal {
  public readonly content: Window | null = null
  constructor(target: string) {
    asyncAppMap(target).then(app => {
      // Not possible currently.
      // this.content = app
    })
  }
}

我正在寻找一些可重复使用的实用程序,例如:

class FrameInternal{}
// Then all members of Frame becomes readonly
export const Frame: ReadonlyClass<FrameInternal> = FrameInternal

1 个答案:

答案 0 :(得分:1)

根据您的特定需求,您可以使用以下内容:

type ReadonlyClass<T extends new (...args: any) => any> =
    T extends new (...args: infer A) => infer R ?
    new (...args: A) => { readonly [K in keyof R]: R[K] } : never;

类型ReadonlyClass将构造函数类型转换为新的构造函数类型,该类型会生成相同的实例类型,其所有属性都标记为readonly

在导出类构造函数时,您可能还希望导出与实例类型对应的具有相同名称的类型。当您使用class Foo {}表示法时,这种情况会自动发生({{1}被引入为类构造函数值的名称和类实例类型的名称):

Foo

检查时,看起来像这样:

export const Frame: ReadonlyClass<typeof FrameInternal> = FrameInternal;
export type Frame = InstanceType<typeof Frame>;

至少应该在上面显示的示例情况下有效:

/*
const Frame: new (target: string) => {
    readonly content: Window | null;
}
type Frame = {
    readonly content: Window | null;
}
*/

好的,希望能有所帮助;祝你好运!

here