Home > Enterprise >  "Element implicitly has an 'any' type because expression of type" in dynamic ind
"Element implicitly has an 'any' type because expression of type" in dynamic ind

Time:12-16

I having trouble with setting typeof variable.

What I have :

let filterStatus:{
'`filter[or][${number}][status]`' ?:string
} = {};

and ${number} is dynamic and I want to assing to my var in this way :


filterStatus[`filter[or][${2}][status]`] = 'pending';

and typescript return this error:


Element implicitly has an 'any' type because expression of type '"filter\[or\]\[2\]\[status\]"' can't be used to index type '{ '`filter[or][${number}][status]`'?: string | undefined; }'.
Property 'filter\[or\]\[2\]\[status\]' does not exist on type '{ '`filter[or][${number}][status]`'?: string | undefined; }'.

it's string structure that the backend wants me to send

see my example in playground

any help would be appreciated

CodePudding user response:

The property of filterStatus is currently not a template literal type. You just hardcoded it to be the string literal filter[or][${number}][status] which does not respect ${number} to be placeholder for a number.

You will have to use a mapped type.

let filterStatus:{
  [K in `filter[or][${number}][status]`]?: string
} = {};

This will give the type of filterStatus an index signature. And those are allowed to be template literal types.

let num = 2;
filterStatus[`filter[or][${num}][status]`] = 'pending'; // valid
filterStatus[`filter[or][2][status]`] = 'pending';      // valid

filterStatus[`filter[or][abc][status]`] = 'pending'; // compile time error

Playground

  • Related