簡體   English   中英

獲取TypeScript中嵌套class的類型

[英]Get the type of a nested class in TypeScript

我通過使用以下代碼在 TypeScript 中使用嵌套類

class Parent {
  private secret = 'this is secret'
  
  static Child = class {
    public readSecret(parent: Parent) {
      return parent.secret
    }
  }
}

這是基於以下答案 它允許我的Child class 訪問Parent class 的私有屬性。

我想用嵌套的 class 類型鍵入一個變量,我天真地開始使用以下代碼:

type NestedType = Parent.Child
const child: NestedType = new Parent.Child()

但我收到以下錯誤:

'Parent' only refers to a type, but is being used as a namespace here. ts(2702)

我嘗試使用typeof運算符:

type NestedType = typeof Parent.Child
const child: NestedType = new Parent.Child()

但它不起作用:

Property 'prototype' is missing in type '(Anonymous class)' but required in type 'typeof (Anonymous class)'. ts(2741)

最后我能夠讓它工作:

const nestedTemplate = new Parent.Child()
type NestedType = typeof nestedTemplate
const child: NestedType = new Parent.Child()

但是,這段代碼創建了一個無用的Child實例。 這是TS語言的限制嗎?

僅供參考,我還嘗試使用名稱空間:

class Parent {
  private secret = 'this is secret'
}

namespace Parent {
  export class Child {
    public readSecret(parent: Parent) {
      return parent.secret
    }
  }
}

但是隨后Child class 不再能夠訪問Parent class 的私有屬性:

Property 'secret' is private and only accessible within class 'Parent'. ts(2341)

使用typeof子原型應該足以解決您的打字問題。

class Parent {
  private secret = 'this is secret'

  static Child = class {
    public readSecret(parent: Parent) {
      return parent.secret
    }
  }
}

const child: typeof Parent.Child.prototype = new Parent.Child();
console.log(child.readSecret(new Parent()));

你可以在那里測試它Playground Link

這樣您就不必實例化任何中間類。

您可以通過接口屬性訪問表示法 ( foo["bar"] ) 訪問Child class:

class Parent {
  private secret = 'this is secret'
  
  static Child = class {
    public readSecret(parent: Parent) {
      return parent.secret
    }
  }
}

type ParentChildProto = (typeof Parent)["Child"];

const child: InstanceType<ParentChildProto> = null!; // same as assigning to `new Parent.Child()`
child.readSecret(new Parent());

TypeScript 游樂場鏈接

編輯:使用內置的InstanceType見評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM