Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Object is possibly 'null'

I'm trying to convert a react project into TypeScript. The code below is an input field that counts how many characters that is being inputed.

In the renderCharactersLeft function I get the following error:

enter image description here

This doesn't really surprise me since the default state 'charsLeft' is set to null, but I wonder how you would bypass or solve this message in TypeScript?

import React from "react";

interface CharCountInputProps {
  value: string;
  type: string;
  name: string;
  maxChars: number;
  onChange: any;
}

interface CharCountInputState {}

class CharCountInput extends React.Component<
  CharCountInputProps,
  CharCountInputState
> {
  state = {
    charsLeft: null
  };

  componentDidMount() {
    this.handleCharCount(this.props.value);
  }

  handleCharCount = (value: string) => {
    console.log(value);
    const { maxChars } = this.props;
    const charCount = value.length;
    const charsLeft = maxChars - charCount;
    this.setState({ charsLeft });
  };

  changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ [event.target.name]: event.target.value } as Pick<
      CharCountInputState,
      keyof CharCountInputState
    >);
    this.handleCharCount(event.target.value);
    this.props.onChange(event);
  };

  renderCharactersLeft = () => {
    const { charsLeft } = this.state;

    let content;
    if (charsLeft >= 0) {
      content = <span>{`characters left: ${charsLeft}`}</span>;
    } else if (charsLeft != null && charsLeft < 0) {
      const string = charsLeft.toString().substring(1);
      content = <span>{`too many characters: ${string}`}</span>;
    } else {
      content = null;
    }
    return content;
  };

  render() {
    const { value, type, name } = this.props;

    return (
      <>
        <input
          onChange={this.changeHandler}
          value={value}
          type={type}
          name={name}
        />
        {this.renderCharactersLeft()}
      </>
    );
  }
}

export default CharCountInput;
like image 822
erikos93 Avatar asked Mar 03 '23 01:03

erikos93


1 Answers

You could add a null check to your if-statement like this:

if (charsLeft !== null && charsLeft >= 0) {

or alternatively set the initial state for charsLeft to something other than null (ex. maxChars from your props)

like image 131
Manaus Avatar answered Mar 05 '23 14:03

Manaus