Strongly typed reflect-metadata
I'm playing a bit with reflect-metadata but something that's bothering me is all the any's in the type definitions. For example:
const value = Reflect.getMetadata('key', Object);
How do we know key is a valid metadata key? And value is any, so, you'd have to remember if it could be undefined or not, and do all sort of type castings to make it usable while relying on your typings.
I'm not saying that TypeScript should automatically be able to infer which keys and values are valid metadata in Object (even tho that'd be great) but at least, I think we should be able to do something like:
interface UserMetadata {
name: string;
age: number;
}
const name = Reflect.getMetadata<UserMetadata>('name', Object); // name is recognized as a valid key and is a string
const age = Reflect.getMetadata<UserMetadata>('age', Object); // age is recognized as a valid key an is a number
const firstName = Reflect.getMetadata<UserMetadata>('firstName', Object); // It complains because firstName is not a a valid key
Or am I missing something and this is possible? So far, I tried to improve the default typings for getMetadata but even tho I got the key validation part right, it's still returning any for the value.
function getMetadata<T, K extends keyof T = keyof T>(metadataKey: K, target: Object): T[K];
What do you think?