給定以下串列:
const list = ["A", "B", "C"] as const;
type List = typeof list[number];
我有一張必須包含所有可能鍵的地圖list:
const mapping: Record<List, unknown> = {
A: true,
B: 2,
C: "three"
};
就像我可以強制mappingmap over 一樣List,我想對型別做同樣的事情。像這樣的東西(我知道這是一個無效的語法):
type MappedList: Record<List, unknown> = {
A: boolean,
B: number,
C: string
}
我的主要目標是防止出現我將新單元格添加到list并忘記將其添加到MappedList.
看游樂場
uj5u.com熱心網友回復:
AFAIK,沒有型別的型別這樣的概念。但是,您可以使用映射型別從另一種型別創建一種型別。
const list = ["A", "B", "C"] as const;
type ListKey = typeof list[number];
// type MappedList = {
// A: "property";
// B: "property";
// C: "property";
// }
type MappedList = {
[Prop in ListKey]: 'property'
}
據我了解,您還需要確保Ais a boolean,Bis anumber和Cis a string。為此,您需要創建一個映射和條件型別:
const list = ["A", "B", "C"] as const;
type ListKey = typeof list[number];
type TypeMap = {
A: boolean,
B: number,
C: string
};
/**
* If T is a subtype of TypeMap
* and keyof T extends keyof TypeMap
*/
type BuildMappedList<T> = T extends TypeMap ? keyof T extends keyof TypeMap ? T : never : never;
/**
* Ok
*/
type MappedList = BuildMappedList<{
A: true,
B: 2,
C: "three",
}>
/**
* Never
*/
type MappedList2 = BuildMappedList<{
A: true,
B: 2,
C: "three",
D: [2] // because of extra D property
}>
/**
* Never
*/
type MappedList3 = BuildMappedList<{
B: 2,
C: "three",
}> // because no A property
/**
* Never
*/
type MappedList4 = BuildMappedList<{
A: false,
B: [2], // because B is not a number
C: "three",
}>
在此處輸入鏈接描述
uj5u.com熱心網友回復:
您可以通過創建一個需要泛型匹配的實用程式來做到這一點:
type AssertKeysEqual<
T1 extends Record<keyof T2, any>,
T2 extends Record<keyof T1, any>
> = T2
const list = ["A", "B", "C"] as const;
type ListKey = typeof list[number];
const mapping: Record<ListKey, unknown> = {
A: true,
B: 2,
C: "three",
};
type MappedList = AssertKeysEqual<Record<ListKey, unknown>, {
A: boolean;
B: number;
C: string;
}>
打字稿游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407285.html
標籤:
上一篇:你如何在Typescript中為函式就地解構撰寫型別?
下一篇:檢查打字稿型別映射中的空型別
