如何在打字稿中定义对象键的类型

时间:2020-06-04 11:49:03

标签: typescript

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

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 };

2 个答案:

答案 0 :(得分:2)

您需要为此使用适当的接口,而不要使用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 };

答案 1 :(得分:2)

您可以创建一个界面:

像这样->

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

然后在类内创建对象->

    private DBConfig: IdBConfig;

因此您可以在构造函数上对其进行初始化,就像您做的一样:=>

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