erik-sn
erik-sn

Reputation: 2600

Correct Usage of React.Events in TypeScript 2.0?

I have an app using React and TypeScript. I recently updated my type definitions to use the npm @types namespace to store them in my node_modules folder.

Previously when working with DOM Events a method signature like this satisfied the type definitions:

public updateValue(e: React.FormEvent): void {

Now However I get compiler errors:

(46,25): error TS2314: Generic type 'FormEvent<T>' requires 1 type argument(s).  

And after looking in the react type definitions folder it does indeed take in a generic:

interface FormEvent<T> extends SyntheticEvent<T> {
}

My question is basically what is the use case for this generic, how should it be used and what advantages does it add? I could simply change my method to:

public updateValue(e: React.FormEvent<any>): void {

And this would satisfy the type definition requirement. But what is the intended use case?

Upvotes: 4

Views: 429

Answers (1)

Paarth
Paarth

Reputation: 10397

From reading the react.d.ts file you've linked, it looks like that generic parameter corresponds to the HTMLElement specified in the currentTarget property. The Mozilla Docs would indicate this is typically an Element.

[currentTarget: EventTarget & T;]

T remains unspecified up to

interface ReactHTMLElement<T extends HTMLElement> extends DOMElement<HTMLAttributes<T>, T> {

which seems to support the idea that T is an element. I believe the goal of the generic is being able to access element-specific properties (src tags and such using HTMLImageElement, for example) on the currentTarget property. There's an issue that suggests doing something similar in the core lib.d.ts along with some discussions on issues involved.

From what I can tell the react typing is an implementation of that same core idea.

Upvotes: 3

Related Questions