React TypeScript: How to make a ref using c => (this.c = c)?

Viewed 724

NOTE: I asked this question previously. Tolle you marked that question as a duplicate of this question. But it is different, in that in my case the ref is created this way:

ref={slider => (this.slider = slider)}

And in your proposed original question this way:

ref={this.stepInput}

The answer for your proposed original was to do it this way:

private sliderRef = createRef<Slider>();
// ...
<Slider {...settings} slide={classes.slide} ref={this.sliderRef}>

But then I can't do:

next = () => {
  this.sliderRef.slickNext();
};

because I get the error:

[ts] Property 'slickNext' does not exist on type 'RefObject<Slider>'.

With this being said, here is the question:

I'm building a React app using TypeScript. I'm using React-Slick's carousel.

I'm trying to programmatically change the slide of the carousel. Therefore I followed the documentation and tried to create a ref for the Slider.

<Slider ref={slider => (this.slider = slider)} {...settings}>

Now TypeScript complains that it does not know slider. So I tried declaring it like this:

slider: Slider | null;

If I try it like this, I get the error:

[ts] Property 'slider' has no initializer and is not definitely assigned in the constructor.

How is one supposed to make a ref work with TypeScript?

The only way I could find was to say:

slide: any;

which defeats the purpose of TypeScript .

0 Answers
Related