我想要一個 TypeScript 物件文字常量,其中包含已知但很長的屬性串列,這些屬性都具有相同的型別。下面是型別的定義和只有三個屬性的簡化示例。
type ContainerSize = {
height: string;
width: string;
threshold?: number;
};
const CONTAINER_SIZES = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
上面定義的問題在于屬性型別不是ContainerSize. 這可以通過使用Record<string, ContainerSize>作為物件型別來修復:
const CONTAINER_SIZES: Record<string, ContainerSize> = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
但是現在任何字串都是有效的鍵,因此CONTAINER_SIZES['not-existing']不會顯示錯誤。
除了像下面的示例那樣將屬性寫入兩次之外,還有其他方法可以定義物件字面量嗎?
const CONTAINER_SIZES: Record<'/' | '/info' | 'default', ContainerSize> = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
uj5u.com熱心網友回復:
兩種選擇:
首先通過單獨定義物件來推斷鍵
一個回傳的什么都不做的函式
ContainerSize
從前一個物件推斷鍵
它必須能夠做到這一點的一個步驟,但這里是你如何可以通過兩個步驟來做到:
const _sizes = {
'/': { height: '65px', width: '220px' },
'/info': { height: '220px', width: '220px' },
default: { height: '700px', width: '500px', threshold: 480 },
} as const;
const CONTAINER_SIZES: Record<keyof typeof _sizes, ContainerSize> = _sizes;
游樂場鏈接
正如您所指出的(謝謝!),這失去了屬性值(CONTAINER_SIZE的屬性值和ContainerSize物件的值)的只讀方面,我們可以Readonly在兩個地方修復它:
const CONTAINER_SIZES: Readonly<Record<keyof typeof _sizes, Readonly<ContainerSize>>> = _sizes;
游樂場鏈接
無所作為的功能
我ContainerSize在提供值(開發人員體驗的東西)時想要強制執行時使用的另一個選項是具有無所作為的功能:
const cs = (size: ContainerSize) => size;
然后:
const CONTAINER_SIZES = {
'/': cs({ height: '65px', width: '220px' }),
'/info': cs({ height: '220px', width: '220px' }),
default: cs({ height: '700px', width: '500px', threshold: 480 }),
};
這為傳入的物件文字中的屬性名稱等提供了自動完成功能cs。(在我做這件事的一個專案中,我很快發現我想在函式中添加一些跨屬性驗證邏輯,所以它最終不是什么都不做......)
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377270.html
標籤:打字稿
上一篇:使兩個引數可選,但如果在TypeScript中至少指定了一個,則這兩個引數都是必需的
下一篇:根據條件添加道具以反應組件?
