在 TypeScript 中,我有這樣的記錄:
const entityTypeExemptPayeeCodeMap: Record<EntityType, readonly PayeeCode[]> = {
[EntityType.Smllc]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.Llc]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.CCorp]: [1, 2, 3, 4, 5, 6, 7, 9, 11, 12],
[EntityType.SCorp]: [1, 2, 3, 4, 5, 6, 7, 9, 11, 12],
[EntityType.Partnership]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.TrustEstate]: [1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13],
[EntityType.Other]: [1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13],
} as const;
我想從記錄中的一個陣列中獲取一個數字聯合型別。我認為這可能有效:
type SmllcExemptPayeeCodes = typeof entityTypeExemptPayeeCodeMap[EntityType.Smllc]
但這只是給了我一種型別,readonly PayeeCode[]而不是陣列中值的聯合。
如果我不做entityTypeExemptPayeeCodeMap記錄,像這樣:
const entityTypeExemptPayeeCodeMap = {
[EntityType.Smllc]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.Llc]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.CCorp]: [1, 2, 3, 4, 5, 6, 7, 9, 11, 12],
[EntityType.SCorp]: [1, 2, 3, 4, 5, 6, 7, 9, 11, 12],
[EntityType.Partnership]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.TrustEstate]: [1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13],
[EntityType.Other]: [1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13],
} as const;
然后SmllcExemptPayeeCodes就像我所期望的那樣成為一個工會。有什么方法可以保留 Record 型別entityTypeExemptPayeeCodeMap并仍然檢索聯合?
在上面的例子中,EntityType 是:
enum EntityType {
Smllc = "smllc",
Llc = "llc",
CCorp = "cCorp",
SCorp = "sCorp",
Partnership = "partnership",
TrustEstate = "trustEstate",
Other = "other",
}
收款人代碼是:
type PayeeCode = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13;
uj5u.com熱心網友回復:
我認為這可能有效:
type SmllcExemptPayeeCodes = typeof entityTypeExemptPayeeCodeMap[EntityType.Smllc]
...
如果我
entityTypeExemptPayeeCodeMap不成為 aRecord,像這樣:...然后SmllcExemptPayeeCodes像我期望的那樣成為一個工會。
這很奇怪,我希望你需要[number]。
有什么方法可以保留 Record 型別
entityTypeExemptPayeeCodeMap并仍然檢索聯合?
我不這么認為,TypeScript 會聽從你說的;但您可以使用中間變數(codeMap在本例中):
const codeMap = {
[EntityType.Smllc]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.Llc]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.CCorp]: [1, 2, 3, 4, 5, 6, 7, 9, 11, 12],
[EntityType.SCorp]: [1, 2, 3, 4, 5, 6, 7, 9, 11, 12],
[EntityType.Partnership]: [1, 2, 3, 4, 6, 7, 11, 12],
[EntityType.TrustEstate]: [1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13],
[EntityType.Other]: [1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13],
} as const;
const entityTypeExemptPayeeCodeMap: Record<EntityType, readonly PayeeCode[]> = codeMap;
type SmllcExemptPayeeCodes = (typeof codeMap)[EntityType.Smllc][number];
// ^? type SmllcExemptPayeeCodes = 1 | 2 | 3 | 4 | 6 | 7 | 11 | 12
游樂場鏈接
那么如果你想讓事情只使用Record版本,只暴露entityTypeExemptPayeeCodeMap給其他代碼而不是codeMap.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/433046.html
標籤:打字稿
