簡體   English   中英

如何強制 Typescript 檢查 object 中的所有鍵是否存在於數組中,其中所述鍵用作值?

[英]How to enforce Typescript to check that all keys in an object are present in array, where said keys are used as a value?

是否有任何簡單的方法可以確保 object 的所有鍵都存在於另一個 object 屬性上?

例如:

export interface Field<T> {
  formKey: Extract<keyof T, string>;
  label: string;
  text: string;
}

export interface FormProps<T> {
  initState: T;
  fields: Field<T>[];
  title: string;
}


const initState = {
 name: 'whatever',
 description: 'whocares'
}

Typescript 是否可以檢查fieldsinitState中存在的所有鍵是否存在於該對象數組中,這些鍵被分配給formKey

所以如果你通過了:

const mockExposureProps: FormProps<FormInfo.Exposure> = {
  fields: [
    {
      formKey: "description",
      label: "mock-label",
      text: "mock-text",
    },
  ],
  initState: {
    description: "mock-desc",
    name: "mock-name",
  },
  title: "cool title",
};

Typescript 會讓你知道,你還沒有通過一個名為formKeyname

編輯:

我能得到的最接近的是:

export interface Field<T> {
  formKey: Pick<T, keyof T>; // Change occurred here
  label: string;
  text: string;
}

但是隨后我的數據結構需要更改為:

const mockExposureProps: FormProps<FormInfo.Exposure> = {
  fields: [
    {
      formKey: { // Change occurred here
        description: 'mock-desc',
      }
    },
      label: "mock-label",
      text: "mock-text",
    },
  ],
  initState: {
    description: "mock-desc",
    name: "mock-name",
  },
  title: "cool title",
};

雖然可以通過使用幫助器 function 以非常全面的方式強制執行它,如圖所示: 確保數組具有聯合中的所有類型

我認為這在 react 和在組件中使用它的上下文中不會真正起作用。 相反,我建議將類型定義更改為:

export interface Field {
  label: string;
  text: string;
}

export interface FormProps<T> {
  initState: T;
  fields: Record<keyof T, Field>;
  title: string;
}

通過這種方式,您可以輕松地強制 initState 中存在的每個鍵也必須存在於字段中。

操場

暫無
暫無

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

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