I'm using a generic mapped type to add meta data to entity types. I get an error when I try to access optional properties in the meta type.
Type definitions:
interface Entity {
id: number;
title: string;
}
interface EntityMeta<T> {
required: {
[Property in keyof T]?: true;
};
}
Use:
const entity: Entity = {
id: 1,
title: "test"
};
const meta: EntityMeta<Entity> = {
required: {
id: true
}
};
Object.entries(entity).forEach(([key, value]) => {
console.log(`${key} = ${value}, Is required: ${meta.required[key] ? 'yes' : 'no'}`)
})
The semantics here is that I want to be able to say which subset of entity properties are required and then to access this meta data when I map over entity properties later.
The error is on that last line: meta.required[key]
Error message:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ id?: true | undefined; title?: true | undefined; }'. No index signature with a parameter of type 'string' was found on type '{ id?: true | undefined; title?: true | undefined; }'.
It's easy to access these properties directly:
const isIdRequired = meta.required.id;
But, I need to access them dynamically via a string key.
How do I best fix this in Typescript?
Thanks,