I want to type the following nested object. the type works when you assign it to an object, but is there a way to make it work while accessing its properties?
type NestedObject = {
[key: string]: NestedObject | string;
}
const obj: NestedObject = {
a: '123',
b: {
b_a: {
b_a_a: '456'
},
b_b: '789'
}
};
function ABC(myNestedObject: NestedObject) {
const nestedObject: NestedObject = {
// Property 'fail' does not exist on type 'string | NestedObject'.
'failProperty': myNestedObject.properties.fail
};
}
I tried to make it conditional by checking whether it extends from string, but I'm having challenges accessing the current value for the specified key. This for instance, doesn't work:
type NestedObject = {
[K in NestedObject]: NestedObject[K] extends string ? string : NestedObject;
}
You need to narrow down whether the .properties property is a string or a NestedObject. If it's a string, then referencing myNestedObject.properties.fail would result in problems - which is why TypeScript is warning you about it.
Construct the code paths so that if the typeof results in string, you don't reference myNestedObject.properties.fail.
function ABC(myNestedObject: NestedObject) {
if (typeof myNestedObject.properties === 'string') {
throw new Error();
}
const nestedObject: NestedObject = {
// Property 'fail' does not exist on type 'string | NestedObject'.
'failProperty': myNestedObject.properties.fail
};
}