Michael Durrant
Michael Durrant

Reputation: 96484

TypeScript error: Property 'target' does not exist on type 'Object' for event handler

I'm converting a React file to typescript, changing from .js to .tsx

I have event handlers such as

function handleTitle(e) {
  setTitle(e.target.value);
}

which I changed to

function handleTitle(e:object) {
  setTitle(e.target.value);
}

but with the change I am getting

TypeScript error: Property 'target' does not exist on type 'object'

I tried e:object, e:array, e:any and e:string

Upvotes: 2

Views: 1834

Answers (1)

Sinane
Sinane

Reputation: 1990

e: React.YOUR_EVENT<YOUR_ELEMENT>

For an "onChange" event on an input:

function handleTitle(e: React.ChangeEvent<HTMLInputElement>) {
  setTitle(e.target.value);
}

DRY options:

Type the event

type OnChangeEvent = React.ChangeEvent<HTMLInputElement>

function handleTitle(e: OnChangeEvent) {
  setTitle(e.target.value);
}

Type the function (parameter and return type)

type HandleTitleType = (e: React.ChangeEvent<HTMLInputElement>) => void

const handleTitle: HandleTitleType = (e) => {
  setTitle(e.target.value);
}

Upvotes: 4

Related Questions