如何定义一个映射,其中每个键都分配有特定类型?
这是类型定义:
type Data = {
articles: Article[],
comments: Comment[],
...
}
map def 必须只接受该类型的键,但值必须与键匹配:
type MyMap = <K extends keyof Data>Map<K, Data[K]>; // <- doesn't work
您可以创建一个通用类型,它使用分布式条件类型
type MyMap<O, K extends keyof O = keyof O> = K extends any ? Map<K, O[K]> : never;
这将为来自
Map
的每个键 (K
) 以及关联的值类型 (Data
) 构建 O[K]
类型的并集:
type MyDataMap = MyMap<Data>;
// Map<"articles", Article[]> | Map<"comments", Comment[]>
// Define a map where keys have specified types
const typeCheckedMap = {
key1: 'string',
key2: 'number',
key3: 'boolean',
};
// Function to check if the value matches the specified type
function checkType(key, value) {
const expectedType = typeCheckedMap[key];
const actualType = typeof value;
if (expectedType !== actualType) {
console.error(`Type mismatch for key ${key}. Expected type: ${expectedType}, Actual type: ${actualType}`);
return false;
}
return true;
}
// Example usage
const map = {
key1: 'Hello',
key2: 42,
key3: true,
};
for (const key in map) {
if (map.hasOwnProperty(key)) {
if (!checkType(key, map[key])) {
// Handle type mismatch
// You can decide what to do in case of a type mismatch
// For example, skip, log an error, or throw an exception
}
}
}