【发布时间】:2020-06-11 18:14:02
【问题描述】:
假设我有三个对象
const common = {
app: {
port: 8080
}
};
const development = {
app: {
port: 5000
}
};
const production = {};
我想为这些对象创建一个接口,但是对于名称为 common 的对象,所有字段都是必需的,但其他人可能会跳过这些字段,因为如果不存在,稍后将从 common 中挑选这些字段。
我已经创建了一个这样的界面
export interface Settings {
app: { port: number }
}
现在,common 将像这样实现这个接口:
import { Settings } from "./types";
/** common should implement all the fields defined in Settings interface */
const common: Settings = {
app: {
port: 8080
}
};
我希望 development 和 production 对象也实现 Settings 接口,但应该允许它们跳过字段
如果我执行const production: Settings = {},我会收到预期的错误,因为我没有定义Settings 接口的所有必需属性。为了解决这个问题,我正在这样做:
export interface OptionalSettings {
app?: { port?: number }
}
我创建了一个新接口OptionalSettings,现在我的development 和production 对象实现了OptionalSettings 接口,而不是像这样的Settings 接口
const prodSettings: OptionalSettings = {}
现在,我的代码按预期工作,除了Settings 接口中定义的属性外,我不能使用任何其他属性,也可以跳过它们。由于这不是一个理想的解决方案,我不得不让两个接口保持同步。一个有值,另一个有可选值。有没有更直接的方法?
下面是我的接口文件
export interface Settings {
app: { port: number }
}
export interface OptionalSettings {
app?: { port?: number }
}
【问题讨论】:
-
您可以使用内置的
Partial类型助手。例如:type OptionalSettings = Partial<Settings>。如果您需要嵌套属性是可选的,you can define your own recursive partial type,然后使用type OptionalSettings = RecursivePartial<Settings>。 -
感谢您将我重定向到递归部分,因为我希望嵌套属性也是可选的
标签: javascript typescript interface