有沒有什么簡單的方法可以確保一個物件的所有鍵都存在于另一個物件屬性上?
例如:
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 是否可以檢查 forfields中initState存在的所有鍵,是否存在于該物件陣列中,這些鍵被分配給了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",
};
打字稿將讓你知道,你也沒通過,有一個物體formKey的name
編輯:
我能得到的最接近的是這個:
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",
};
uj5u.com熱心網友回復:
雖然可以通過使用輔助函式以非常全面的方式強制執行它,如下所示:確保陣列具有聯合中的所有型別
我認為這在 react 的背景關系中并不會真正起作用并在組件中使用它。相反,我建議將型別定義更改為:
export interface Field {
label: string;
text: string;
}
export interface FormProps<T> {
initState: T;
fields: Record<keyof T, Field>;
title: string;
}
通過這種方式,您可以輕松地強制 initState 中存在的每個鍵也必須存在于欄位中。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369134.html
上一篇:在嘗試運行示例時,打字稿中的簡單react-dnd串列給了我編譯錯誤
下一篇:TypeScript中的條件道具
