簡體   English   中英

Typescript 接口用於相同類型的對象,但必須具有所有字段,而其他可能跳過字段

[英]Typescript interface for same type of objects but one must have all the fields while others may skip the fields

假設我有三個對象

const common = {
   app: {
     port: 8080
   }
};

const development = {
   app: {
     port: 5000
   }
};

const production = {};

我想為這些對象創建一個接口,但是對於名稱為common的 object,所有字段都是必需的,但其他人可能會跳過這些字段,因為如果不存在,這些字段將在以后從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

 export interface Settings { app: { port: number } } interface MyType extends Settings {} const foo:Partial<MyType> = {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM