const parent2 = {child: 'name'}
const index2: string = 'child';
const child3 = parent2[index2]
When I try to access child in parent2 I get the following error
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ child: string; }'.
No index signature with a parameter of type 'string' was found on type '{ child: string; }'
Is there an easy way to make parent2[index2] return 'name' | undefined ?
It's even more difficult to deal with nested readonly object. allowStringIndex type keeps index autocomplete and it allows accesing properties using string, but it's annoying to construct the type. Is there an easy way to access nestedObject[grandParentIndex]?.[parentIndex]
const nestedObject = {grandParent: {name: 'grandparent', parent: {name: 'parent', child: {name: 'child'}}}} as const;
type child = {name: 'child', [key: string]: 'child' | undefined}
type parent = {name: 'parent', child: child}
type overrideParent = parent & {[key: string]: parent[keyof parent] | undefined}
type grandParent = {name: 'grandparent', parent: overrideParent}
type overrideGrandParent= grandParent & {[key: string]: grandParent[keyof grandParent] | undefined}
type allowStringIndex = {grandParent: overrideGrandParent} & {[key: string]: overrideGrandParent | undefined}
const castedObject = nestedObject as allowStringIndex;
const grandParentIndex: string = 'grandparent';
const parentIndex: string = 'parent'
const child = nestedObject[grandParentIndex]?.[parentIndex]?.['child']
const parent1 = castedObject[grandParentIndex]?.[parentIndex]
Why are you explicitly typing your string consts with
: stringinstead of letting TypeScript infer the value? You can just remove those. Also, you seem to have misspelled the string assigned tograndParentIndex, it should be"grandParent"not"grandparent"?