代码之家  ›  专栏  ›  技术社区  ›  user3322378

NextJS Typescript-对象可能未定义-NextJS构建失败

  •  0
  • user3322378  · 技术社区  · 2 年前

    我是打字脚本的新手,一直被困在nextjs构建中。代码在我的浏览器中运行得很好,但当我尝试执行nextjs构建时,我会收到以下错误。在网上查找后,我尝试了一些方法,但没有成功。我点击按钮调用测试函数。

    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')){
    

    代码:

    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"]
    }
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Dave    2 年前

    具有 const [value, setValue] = useState<string|null>('const pi = 3.14;'); 你在告诉打字稿 value 可能为null。由于您从未将其设置为null,因此可以安全地进行更改 useState<string | null> useState<string> .

    从那以后 value!.split('```javascript').pop().split('```')[0] 可能是 undefined ,您可以将其更改为 value.split('```javascript').pop()?.split('```')[0] ?? '' 利用 零合并运算符 或将其更改为 value.split('```javascript').pop().split('```')[0] 并将'js'state的类型调整为 const [js,setJs] = useState<string | undefined>('')

    您也可以删除 ! 访问时 价值 变量具有 ! 你在告诉typescript编译器:“嘿,这不可能 未定义 null ,所以不要抱怨这种可能性”。