I am looking to create a custom type that allows access to undefined properties of an object with the type of any
, and does so recursively. To better illustrate the issue, I have included a simplified and corrected example below based on feedback received.
const data = {a: "a", b: {c: 'hey'}}
type Data = typeof data & { [key: string]: any }
const dataOptional: Data = data
// This errors:) as expected, because the property "a" does not have such method
dataOptional.a.nonExistentStringMethod
// These do not error:) as expected, because d has the correct type of "any"
dataOptional.d
dataOptional.d.nonExistentStringMethod
// This does error:( highlighting the problem with this type
dataOptional.b.d
The issue with the current implementation is that it does not apply recursively. It is important to note that I start with the JSON value of data
and need to generate TypeScript code that allows me to export the original data in a way that enables accessing undefined properties as described above.
So my question is, how can I transform a JSON value into TypeScript code that exports the JSON value in a manner where I can recursively access any undefined property with the value of any
, while preserving typing information for defined properties within the original object?