개발하자
TypeScript: 개체가 'null'일 수 있습니다
Cuire
2023. 7. 12. 17:20
반응형
TypeScript: 개체가 'null'일 수 있습니다
리액트 프로젝트를 TypeScript로 변환하려고 합니다. 아래 코드는 입력되는 문자 수를 카운트하는 입력 필드입니다.
renderCharactersLeft 함수에서 다음 오류가 발생합니다:
기본 상태 'charsLeft'가 null로 설정되어 있기 때문에 별로 놀랍지는 않지만, 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;
다음과 같이 if-statement에 null 검사를 추가할 수 있습니다:
if (charsLeft !== null && charsLeft >= 0) {
또는 chars의 초기 상태를 null이 아닌 다른 상태로 설정합니다(예: propet의 maxChars)
또는 로컬 변수를 생성하고 charLeft를 할당한 후 로컬 변수를 비교에 사용할 수 있습니다.
let newVariable = charLeft;
if(newVariable > 0) {
//do coding
}
반응형