reactjstypescriptnext.jsreact-typescript

NextJS Typescript - Object is possibly undefined - nextjs build failure


I am new to typescript and have been stuck in nextjs build. The code code runs perfectly in my browser but when I try to execute nextjs build I am getting the below error. I tried a few methods after looking up online but no success. I am calling test function on click of a button.

Type error: Object is possibly 'undefined'.

  62 |     useEffect(() => {
  63 |         if(value!.includes('javascript')){
> 64 |             setJs(value!.split('```javascript').pop().split('```')[0])
     |                   ^
  65 |         }
  66 |
  67 |         if (value!.includes('html')){

CODE:

const [value, setValue] = useState<string|null>('const pi = 3.14;');
    const [loading, setLoading] = useState(true);
    const [html, setHtml]=useState('')
    const [css,setCss] = useState('')
    const [js,setJs] = useState('')


    useEffect(() => {
        if(value!.includes('javascript')){
            setJs(value!.split('```javascript').pop().split('```')[0])
        }

        if (value!.includes('html')){
            setHtml(value!.split('```html').pop().split('```')[0])
        }

        if (value!.includes('css')){
            setCss(value!.split('```css').pop().split('```')[0])
        }
    },[value])





    const test = async () => {


        try {

            setValue('hi')


        } catch (error) {
            console.log(error);
        }
    };

tsconfig.json:

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts"
  ],
  "exclude": ["node_modules"]
}

Solution

  • With const [value, setValue] = useState<string|null>('const pi = 3.14;'); you are telling typescript that value might be null. Since you are never setting it to null, you can safely change useState<string | null> to useState<string>.

    And since value!.split('```javascript').pop().split('```')[0] might be undefined, you can either change it to value.split('```javascript').pop()?.split('```')[0] ?? '' making use of the nullish coalescing operator or change it to value.split('```javascript').pop().split('```')[0] and adjust 'js' state's type to const [js,setJs] = useState<string | undefined>('')

    You can also remove the ! when accessing the value variable. With ! you are telling the typescript compiler: "hey this can't be undefined or null, so don't complain about the possibility".