簡體   English   中英

使用Typescript接口作為變量

[英]Using Typescript interface as a variable

我正在研究 Node Js (TypeScript) 架構,出於某種原因,我想將我的接口綁定到特定的 object。 我正在制作一個由其他子類擴展的通用 class ,它將有一個非常通用的代碼。 所以我的代碼看起來像

interface User {
  name: string;
}

interface Profile {
  title: string;
}

class Parent {

  name: string;
  interface: Interface; // Help required here, getting error can't use type as a variable
  
  constructor( name, interface ) {
    // Load schema and store here
    
    this.name = name
    this.interface = interface
  }

  // Though this is not correct I hope you get the idea of what I am trying to do
  
  get (): this.interface  {
    // fetch the data and return

    return data
  }

  set (data: this.interface): void {
    // adding new data
  }
}

class UserSchema extends Parent {
  // Class with custom functions for UserSchema
}

class ProfileSchema extends Parent {
  // Class with custom functions for ProfileSchema
}

// Config file that saves the configs for different modules

const moduleConfig = [
  {
    name: "User Module",
    class: UserSchema,
    interface: User
  },
  {
    name: "Profile Module",
    class: ProfileSchema,
    interface: Profile
  },
]

const allModules = {}

// Loading the modules 

moduleConfig.map(config => {
  allModules[config.name] = new config.class(
    config.name, 
    config.interface
  )
})

export allModules;

我需要有關如何將我的接口與它們各自的配置綁定的建議。 到目前為止,我還沒有運氣。

PS:所有這些代碼都被分成各自的文件。

這是generics的用例。 您甚至可以將它們視為“類型的變量”。

而不是在您的Parent class 中具有interface屬性,后者將具有通用類型:

class Parent<T> { // T is the generic type

  name: string;
  // interface: Interface; // generic is already provided at class level
  
  constructor( name ) {
    // Load schema and store here
    
    this.name = name
  }
  
  get (): T  {
    // fetch the data and return

    return data
  }

  set (data: T): void {
    // adding new data
  }
}

// Here you specify the concrete generic type
class UserSchema extends Parent<User> {
  // Class with custom functions for UserSchema
}

class ProfileSchema extends Parent<Profile> {
  // Class with custom functions for ProfileSchema
}

暫無
暫無

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

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