Skip to content
Advertisement

TS7053: TypeScript error when handling input id och input value

I get this Typescript error in terminal:

TS7053: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘CustomForm’. No index signature with a parameter of type ‘string’ was found on type ‘CustomForm’.

when I am trying to implement this solution:

const target = e.target as HTMLInputElement;
this[target.id] = target.value

I have a switch statement where I am checking for target.id. Depending on input id I add value to reactive property in lit component. Here is more of code: A better way to handle input in lit component

Advertisement

Answer

Per the other post you linked, this refers to a Lit component, and the code is meant to be within an event handler for an input element.

TypeScript can’t tell that the id you have on the input element that fires the event will be a valid property on your component.

If you trust that target.id will always be a valid property key, and you allow explicit any for your project, you can suppress TypeScript by doing

const target = e.target as HTMLInputElement;
(this as any)[target.id] = target.value;

Or cast the target.id as a union of possible properties:

const target = e.target as HTMLInputElement;
this[target.id as 'prop1' | 'prop2'] = target.value;

If prop1 and prop2 are valid properties on the component, TS should no longer error.

If you want actual runtime checking that id is valid, you have a couple of options.

You can keep the switch statement you have in your other post but type narrowing will allow you to combine all valid cases:

const target = e.target as HTMLInputElement;
switch (target.id) {
  case 'prop1':
  case 'prop2':
    this[target.id] = target.value;
    break;
  default:
    return;
}

Alternatively, you can also define an array of valid properties:

const target = e.target as HTMLInputElement;
const validKeys = ['prop1', 'prop2'] as const;
const id = target.id as typeof validKeys[number]; // equivalent to 'prop1' | 'prop2'
if (validKeys.includes(id)) {
  this[id] = target.value;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement