I am new to TypeScript and have encountered many similar questions. I was able to find a solution, but I'm not sure if it's the most efficient one.
When constructing the target
object as
{obj: someObject, prop: "objectPropName"}
, I pass it to various React components as a prop. The type of someObject
can vary among about 20 different types, each corresponding to a data model in my database. Naturally, I want to ensure type safety.
My ideal scenario would involve specifying the type of target
as:
type ObjWithPropertyName = {
obj: Record<string, unknown>,
property: **keyof obj**
}
...but unfortunately, that doesn't quite work :)
The best solution I came up with is to create a function that returns a properly-typed target object:
function getTarget<T>(obj: T, propName: keyof T) {
return {obj: obj, property: propName}
}
However, this approach seems a bit messy, especially on the receiving component side where I have to do something similar when handling the target object as a prop.
How would you approach this situation?