我有一个简单的检查,我想检查给定变量是否> = 0。
public print(value: any): void {
if(value >= 0) {
console.log('Greater than zero')
}
}
这里的问题是当传入变量的值为null时,它将变为true,并记录该语句。有没有一种干净的方法可以避免这种情况,但是不添加额外的检查?
答案 0 :(得分:1)
我不明白您为什么不想添加空检查。
另一种方法是使用number
而不是any
,但是只有在您的ts.conf
启用严格的空检查后,它才有效。
function print(value: number): void {
if(value >= 0) {
console.log('Greater than zero')
}
}
print(null) // won't compile with strict null checks
答案 1 :(得分:1)
如果您的代码库不允许使用null
,则只需使用undefined
并使用隐式转换,就像这样:
public print(value: any): void {
if(value != undefined && value >= 0) {
console.log('Greater than zero')
}
}
之所以有效,是因为null == undefined
(双等于创建类型转换,而三等于则没有)。
答案 2 :(得分:0)
您可以使用type guard来确保编译器不会处理null
而是数字。而且,这将使代码更加正确,因为使用value: any
意味着您可能会传入布尔值或字符串:
public print(value: any): void {
if (typeof value === "number") {
//value is definitely a number and not null
if (value >= 0) {
console.log('Greater than zero')
}
}
}
现在,代码专门验证您确实获得了一个数字,然后检查该数字是否大于或等于零。这意味着将不会处理null
或非数字值。
为了简洁起见,可以将类型保护条件与其他条件组合在一起:
public print(value: any): void {
if (typeof value === "number" && value >= 0) {
console.log('Greater than zero')
}
}
或单独提取以减少嵌套:
public print(value: any): void {
if (typeof value !== "number")
return;
//value is definitely a number and not null
if (value >= 0) {
console.log('Greater than zero')
}
}
答案 3 :(得分:0)
在 JavaScript 中,我通常使用以下内容:
`${value}` >= 0
// or
parseInt(value) >= 0
在 TypeScript 中,您最有可能使用:
public print(value: any): void {
if (+`${value}` >= 0) {
console.log('Not less than zero')
}
}