如何创建值为函数的Map对象?代码实现咨询
Hey there! Your core approach to creating a Map from an array of key-value pairs is actually correct—Map's constructor accepts exactly that kind of iterable. But let's walk through common issues you might be hitting, plus ways to make this code more robust and type-safe (since you're using TypeScript):
1. Improve Type Safety (Avoid Broad Function Type)
Using Function as the value type is pretty vague, which can lead to type errors down the line. Instead, define a specific type for your entity-transforming functions:
// First, define what your Entity type looks like (adjust this to match your actual data) type Entity = { // Example properties—replace with your real entity structure id: string; createdAt: string; // ... other properties }; // Create a type for your transformation functions type EntityTransformer = (entity: Entity) => Entity; // Now define your dictionary with strict types const entityTagDictionary = [ ['GRAPH_ADD_PROPERTY_SUBTYPE', (entity: Entity) => { console.log('addSubtype called!'); return entity; }], ['GRAPH_IGNORE_PROPERTY_SENTENCE', (entity: Entity) => { console.log('ignore property called!'); return entity; }], ['GRAPH_FORMAT_DATES', (entity: Entity) => { console.log('formatDates called!'); return { ...entity, createdAt: new Date(entity.createdAt).toISOString() }; }], ] as const; // 'as const' locks in the exact keys and function signatures // Initialize your Map with the proper type const entityMap: Map<string, EntityTransformer> = new Map(entityTagDictionary);
2. Correctly Use Functions from the Map
If you're struggling to invoke the functions stored in the Map, here's how to safely retrieve and call them:
// Sample entity to test with const sampleEntity: Entity = { id: '123', createdAt: '2024-01-01' }; // Get the function by its key const formatDatesFn = entityMap.get('GRAPH_FORMAT_DATES'); // Always check if the function exists before calling (Map.get returns undefined for missing keys) if (formatDatesFn) { const updatedEntity = formatDatesFn(sampleEntity); console.log('Updated entity:', updatedEntity); }
3. Fix Common Pitfalls
- Missing key checks: Never assume
Map.get()will return a function—always add a guard clause to avoid runtime errors. - Vague types: Using
Functionhides type issues; definingEntityTransformerensures your functions follow a consistent signature. - Accidental modifications:
as constmakes your dictionary read-only, so you can't accidentally change keys or function signatures later.
If you're seeing a specific error (like a TypeScript compile warning or a runtime bug), share the details and we can dive deeper!
内容的提问来源于stack exchange,提问作者Baptiste Arnaud

