0

I am getting a Property 'checked' does not exist on type 'Switch'. message from TypeScript for this.checked and this.disabled createRefs. Also, on the last line, I am also getting a Property 'checked' does not exist on type 'Switch warning from TS. How can I fix these warnings?

interface Props {
  checked: boolean;
  onChange: (checked: boolean) => void;
  disabled?: boolean;
}

interface States {
  checked: boolean;
  disabled?: boolean;
}

export default class Switch extends React.PureComponent<Props, States> {
  constructor(props: any) {
    super(props);
    this.checked = React.createRef(); // comment this line out to use as controlled component
    this.disabled = React.createRef(); // comment this line out to use as controlled component
    this.state = {
      checked: false,
      disabled: false,
    };
  }

  render() {
    ...
    <div ref={this.checked}> // TypeScript warns: Property 'checked' does not exist on type 'Switch'
Eddie Lam
  • 579
  • 1
  • 5
  • 22

1 Answers1

0

Your issue is that you need to define this variables before using them with this. Just define them private or public or what you want. It type will be the result of a React.createRef() so an React.RefObject object. If you know on which node element you will use the ref, then you can precise it in the type.

For example you use this.checked on a div, so you can define it like React.RefObject<HTMLDivElement>. If you don't know it yet, use React.RefObject<unknown>:

export default class Switch extends React.PureComponent<Props, States> {
  private checked: React.RefObject<HTMLDivElement>;
  private disabled: React.RefObject<unknown>;

  constructor(props: any) {
    super(props);
    this.checked = React.createRef(); // comment this line out to use as controlled component
    this.disabled = React.createRef(); // comment this line out to use as controlled component
    this.state = {
      checked: false,
      disabled: false
    };
  }

  render() {
    return <div ref={this.checked} />;
  }
}

Edit lucid-galileo-neckr

johannchopin
  • 13,720
  • 10
  • 55
  • 101
  • great. It's asking me to define a type for `private checked`, what should I define it as? Or just use `any`? – Eddie Lam Sep 30 '20 at 07:55