繁体   English   中英

如何在typescript中定义object的key的类型

[英]How to define the type of keys of object in typescript

我正在返回 object,如下所示。
我想定义 object 的键值类型。
但这根本不起作用。
你能给我一些建议吗? 感谢您阅读。

class Config {
  private username: string;
  private password: string;
  private database: string;
  private host: string;
  private dialect: string;
  private DBConfig: object;

  constructor() {
    this.username = "";
    this.password = "";
    this.database = "";
    this.host = "";
    this.dialect = "";
    this.DBConfig = {};
  }

  public getDBConfig(environment: string): Object {
    switch (environment) {
      case "local":
        this.DBConfig = {
          username: "root",
          password: "1234",
          database: "test",
          host: "127.0.0.1",
          dialect: "mysql",
        };
        break;
    }
    return this.DBConfig;
  }
}

export { Config };

您需要为此使用适当的接口而不是object

例如定义DBConfig并且您还需要关心this.DBConfig可以是undefined的情况。

// define an interface
interface DBConfig {
  username: string;
  password: string;
  database: string;
  host: string;
  dialect: 'mysql';
}

class Config {
  private DBConfig?: DBConfig; // <- specify it as a type of property.

  public getDBConfig(environment: 'local'): DBConfig; // <- an override for the 100% case.
  public getDBConfig(environment: string): DBConfig | undefined; // <- an override for other unknown cases
  public getDBConfig(environment: string): DBConfig | undefined { // <- implementation
    switch (environment) {
      case "local":
        this.DBConfig = {
          username: "root",
          password: "1234",
          database: "test",
          host: "127.0.0.1",
          dialect: "mysql",
        };
        break;
    }
    return this.DBConfig;
  }
}

export { Config };

您可以创建一个接口:

像这样->

export interface IdBConfig {
    username: string;
    password: string;
    database: string;
    host: string;
    dialect: string;
}

而不是在 class 中创建您的 object ->

    private DBConfig: IdBConfig;

所以你可以在构造函数上初始化它,就像你做的那样:=>

   this.DBConfig = {
      username: "root",
      password: "1234",
      database: "test",
      host: "127.0.0.1",
      dialect: "mysql",
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM