【发布时间】:2020-06-04 19:29:53
【问题描述】:
我正在使用打字稿。我想在对象中创建特定类型的键。
但这根本行不通。
它给了我一些错误,如下所示。
类“Config”错误地实现了接口“IConfig”。 属性“DBConfig”在“Config”类型中是私有的,但在“IConfig”类型中不是私有的。
成员“DBConfig”隐含地具有“任何”类型。
interface IConfig {
DBConfig: {
username: string;
password: string;
database: string;
host: string;
dialect: string;
};
}
class Config implements IConfig {
private DBConfig;
constructor() {}
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(小写),在你的情况下,如果可能的话,我建议更精确并使用IConfig['DBConfig']。 -
要实现接口成员,您必须将其公开.. 从`private DBConfig;`中删除
private -
该错误消息为您提供了两个重要的信息:您没有公共的
DBConfig来匹配接口,并且您的实现的DBConfig没有指定类型(类型需要匹配输入接口,它需要公开才能算作实现)。
标签: typescript