【问题标题】:Typescript interface for same type of objects but one must have all the fields while others may skip the fields用于相同类型对象的 Typescript 接口,但必须具有所有字段,而其他对象可能会跳过字段
【发布时间】: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
   }
};

我希望 developmentproduction 对象也实现 Settings 接口,但应该允许它们跳过字段

如果我执行const production: Settings = {},我会收到预期的错误,因为我没有定义Settings 接口的所有必需属性。为了解决这个问题,我正在这样做:

export interface OptionalSettings {
    app?: { port?: number }
}

我创建了一个新接口OptionalSettings,现在我的developmentproduction 对象实现了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


【解决方案1】:

您可以扩展接口并使用 Partial

export interface Settings {
    app: { port: number }
}

interface MyType extends Settings {}

const foo:Partial<MyType> = {}

【讨论】:

    猜你喜欢
    • 2017-06-12
    • 2018-07-20
    • 2020-03-19
    • 2020-04-18
    • 2019-11-08
    • 2021-10-08
    • 1970-01-01
    • 2016-02-10
    • 2020-08-28
    相关资源
    最近更新 更多