我正在研究 Node Js (TypeScript) 架構,出于某種原因,我想將我的界面系結到特定物件。我正在制作一個由其他子類擴展的通用類,它將有一個非常通用的代碼。所以我的代碼看起來像
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:所有這些代碼都被分成各自的檔案。
uj5u.com熱心網友回復:
這是泛型的用例。您甚至可以將它們視為“型別的變數”。
后者不是在您的類中具有interface屬性,而是具有泛型型別:Parent
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419748.html
標籤:
上一篇:錯誤[ERR_REQUIRE_ESM]:ES模塊的require()...不支持
下一篇:兩級通用嵌套和Parameters<T>會導致TypeScript錯誤。但是一級有效,沒有Parameter<T>有效。為什么?
