gpt4 book ai didi

javascript - 在另一个函数中使用时变量可能未定义(Typescript“错误 TS2532)

转载 作者:行者123 更新时间:2023-12-03 00:04:59 25 4
gpt4 key购买 nike

所以我们开始尝试 Typescript。我在 Vue 中获得了这个用于查看自动全局组件注册的功能。老实说,我不知道这在 Typescript 中如何翻译。它是 camelCase(fileName.split('/')) 函数内的 fileName

import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'


// other code

requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)

// here
const componentName = upperFirst(
camelCase(
fileName
.split('/')
.pop()
.replace(/\.\w+$/, '')
)
)

Vue.component(
componentName,
componentConfig.default || componentConfig
)
})

typescript 错误 TS2532:对象可能“未定义”

最佳答案

pop返回string | undefined ,因此您可以将其保存在变量中以检查 undefined或者大胆地声称它将始终使用 ! 进行定义:

  fileName
.split('/')
.pop()!
.replace(/\.\w+$/, '')

(实际上并不是那么粗体,因为拆分空字符串将始终返回至少一个包含空字符串的数组,因此 pop 应该解析为一个元素。)

<小时/>

变量检查看起来像这样:

const last = fileName
.split('/')
.pop();
if (last == undefined)
throw Error("This has never happened before.")

// Compiler now will 'know' that last is a string.
camelCase(last.replace(/\.\w+$/, ''));

关于javascript - 在另一个函数中使用时变量可能未定义(Typescript“错误 TS2532),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55002065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com