I want to create a type AnyObject
that can have any arbitrary key and value but error for possibly undefined.
const a = {} as AnyObject
console.log(a.b?.c) // This should be fine
console.log(a.b.c) // This should give a possibly undefined error
And it can be nested, with arrays and functions, like with HTML nodes:
node.children?.[0]?.value
node.properties.onClick
Ofcourse this doesn’t work (it doesn’t error in a.b.c
):
type AnyObject = {
[key: string]: any | undefined
}
Ok from your starting code, I came up with this solution:
type AnyObject = {
[key: string]: Omit<undefined,any>;
}
const a:AnyObject = {
key:null,
key2:undefined,
aa:'aa',
bb:1,
structuredObject:{
},
structuredObject2:{
'aa':'aa',
test_boolean:true,
test_aw_func: () => {},
test_func: function(){}
}
}
Which can be tested on this playground: Playground TS
You can extend Omit<undefined,any>
with Omit<undefined,any> | null
in case you want null values also.
Here’s a TypeScript type that achieves what you want:
type AnyObject = {
[key: string]: AnyObject | any | undefined
}
This recursive type definition ensures:
- Any key access requires optional chaining if you want to access nested
properties - Direct access without optional chaining will trigger the
possibly undefined error - Supports nested objects, arrays, and functions
Example usage:
const obj: AnyObject = {}
obj.a?.b?.c // ✓ OK
obj.a.b.c // ✗ Error: Object is possibly undefined
obj.fn?.() // ✓ OK
obj.arr?.[0]?.prop // ✓ OK
yamumsahobo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1