typescript - 使用布尔常量检查参数是否定义
问题描述
使用 Typescript 2.8.3,我不明白为什么以下代码无法获取在 if 块中定义的参数。
const testFunction = (params?: string) => {
const paramIsDefined = typeof params !== 'undefined';
if (paramIsDefined) {
console.log(params.length);
}
};
我收到此错误:TS2532: Object is possible 'undefined' on the console.log line for the params 变量。
而这段代码有效:
const testFunction = (params?: string) => {
if (typeof params !== 'undefined') {
console.log(params.length);
}
};
我不理解/做错了什么?
解决方案
构造:
if (typeof params !== 'undefined') {
console.log(params.length);
}
是类型保护,因此会影响params
.
if (paramIsDefined)
只是一个if
声明,检查的布尔值确实来自类型检查,但编译器根本不遵循这一点。如果您想将params
表单类型缩小string|undefined
到只string
需要使用类型保护构造或使用断言
推荐阅读
- python - 长python导入路径的缩写
- react-native - 尝试从前端反应本机登录,收到错误:未定义电子邮件
- javascript - undefined 不是对象(评估 '_this.state')
- javascript - 今天之前的 Ant Design 禁用日期和其他自定义日期
- data-structures - 哈希表中的渐近运行时间
- c# - 返回字节数组时的LINQ字符串转换错误
- ruby - Ruby Google Drive API - web_content_link 上的 403 禁止
- c++ - std::complex 的 operator* 返回与复数乘法的手动公式不同的答案
- php - php substr() 和货币符号奇怪的输出
- python - discord.py 按内容获取消息