[英]Variable possibly undefined when used inside another function (Typescript “error TS2532)
So here we go, trying Typescript. 因此,我们开始尝试Typescript。 I got this function for view for my automatic global component registration in Vue. 我在Vue中自动全局组件注册时可以查看此功能。 To be honest I have no idea on how this would translate in Typescript. 老实说,我不知道如何在Typescript中进行翻译。 It's the fileName
inside camelCase(fileName.split('/'))
function. 它的fileName
内camelCase(fileName.split('/'))
功能。
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 error TS2532: Object is possibly 'undefined' 打字稿错误TS2532:对象可能是“未定义”
pop
returns string | undefined
pop
返回string | undefined
string | undefined
, so you can either save that in a variable to check for undefined
or be bold and claim that it will always be defined using !
string | undefined
,因此您可以将其保存在变量中以检查undefined
也可以将其加粗并声称将始终使用!
进行定义!
: :
fileName
.split('/')
.pop()!
.replace(/\.\w+$/, '')
(It is not really that bold because splitting an empty string will always return at least an array containing the empty string, so pop should resolve to an element.) (实际上并不是那么粗体,因为分割空字符串将始终至少返回一个包含空字符串的数组,因此pop应该解析为一个元素。)
Variable check would look something like this: 变量检查看起来像这样:
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+$/, ''));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.