有沒有什麼簡單的方法可以確保一個對象的所有鍵都存在於另一個對象屬性上?
例如:
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",
};
雖然可以通過使用輔助函數以非常全面的方式強制執行它,如下所示:確保數組具有聯合中的所有類型
我認為這在 react 的上下文中並不會真正起作用並在組件中使用它。相反,我建議將類型定義更改為:
export interface Field {
label: string;
text: string;
}
export interface FormProps<T> {
initState: T;
fields: Record<keyof T, Field>;
title: string;
}
通過這種方式,您可以輕鬆地強制 initState 中存在的每個鍵也必須存在於字段中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句