4

I am using the React type definitions for my project. I notice it is missing the focus method on elements in the array returned by the refs property - so I cannot get this example to work. Basically, the compiler says: property 'focus' does not exist on type 'Component <any, any> | Element'. This is because focus exists on type HTMLElement not Element. Either the definition file should specify the return type of refs as | HTMLElement or some other extended interface that includes focus method (I'm not sure which but that's not the point of my question).

My question is: what should I do now? I am stuck from continuing development!

I know I could fork the definition file and patch it myself but this seems to be a problem I keep coming up with in TypeScript and was wondering if there was a less cumbersome solution that means I can move quickly. It seems that I keep having to step out of my tracks in building my app to often do TypeScript patching!

Community
  • 1
  • 1
cubabit
  • 2,527
  • 3
  • 21
  • 34

1 Answers1

1

The quick and dirty solution is to cast to any to opt out of type checking i.e.

 onSubmitEditing={(event) => { 
    (this.refs.SecondInput as any).focus(); 
 }}

Submitting a pull request on DefinitelyTyped would be a nice move....

note: you can become more 'sophisticated' if need be, using "double casting to any"

 type ProperRef = Component <any, any> | HTMLElement

 onSubmitEditing={(event) => { 
    const secondRef =  this.refs.SecondInput as any as ProperRef;
    secondRef.focus(); 
 }}
Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101
  • What is the advantage of the double casting? – cubabit Sep 30 '16 at 16:31
  • @cubabit. In that particular case none. More generally, when casting to `any`, you opt out of type checking for this variable. With double casting you opt out then back in and benefit from typing again for that variable. – Bruno Grieder Oct 01 '16 at 14:51