我正在 Typescript 中编写一个通用函数,以获取一个字符串值并检查它是否为 null、未定义或空字符串并返回 null,或者如果它是实际值则返回已 trim 的值。
讽刺的是,我遇到的问题是,在第二行的函数内 return stringValue.trim();
我收到错误 Object is possible is null or未定义
,我不确定我可以做什么样的检查来解决这个问题。
这是我目前的功能:
const sanitize = (stringValue: string | undefined | null) => {
let emptyString = '';
let nullValue = null;
let undefinedValue = undefined;
if(typeof stringValue === emptyString || typeof stringValue === nullValue || typeof stringValue === undefinedValue){
return null
} else {
return stringValue.trim();
}
}
最佳答案
这里不需要使用 typeof
,直接比较变量即可,这样 TypeScript 就知道你已经排除了那些可能的类型,这就保证了 stringValue
不会是 null
或未定义
:
if(stringValue === '' || stringValue === null || stringValue === undefined)
或者,正如 @DBS 提到的,使用 falsy值并将您的陈述简化为
if (!stringValue)
如果您还想让仅包含空格的字符串返回为 null,您可以将 return 语句更改为 return stringValue.trim() || null
检查 trim 后的值是否变为 ''
正如 @DBS 也提到的,typeof
以字符串形式返回类型。此外,null
对象上的 typeof
将返回 'object'
,而不是 'null'
,这使得此方法更不适用对于这种情况。一般来说,我从来没有真正发现自己需要使用 typeof
,除了一些动态输入验证
关于javascript - 在 Typescript 中编写清理函数来检查 null、未定义和空字符串,并在函数内部出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61125262/