Typescript type refinement unknwon to object and retrieving elements

47 Views Asked by At

Well consider I have a json-loaded data object. The type of a json is defined by:

const myObject: {[p: string]: unknown} = JSON.parse(somestring);

I wish to handle this json as if it would be a dictionary-tree. Now I try to read some child object and iterate over that:

const cfgCookie = cfg.cookie;
if (typeof cfgCookie === "object" && cfgCookie !== null && !Array.isArray(cfgCookie)) {
    const someElement = cfgCookie.maxAge;
}

However now typescript complains that property maxAge does not exist on object. Which is expected. So I try to get it dynamically as "if" it would be a dictionary:

    const someElement = cfgCookie['maxAge'];

This gives the following error:

TS7053: Element implicitly has an 'any' type because expression of type '"maxAge"' can't be used to index type '{}'.   Property 'maxAge' does not exist on type '{}'.

So how would I refine unknown to an indexable object?

0

There are 0 best solutions below