您如何克服打字稿中由函数修改的值的有效断言测试?
How do you overcome valid assert test of value modifed by function, in typescript?
这是我在 deno 中 运行 的打字稿代码。
import { assert } from "https://deno.land/std/testing/asserts.ts"
interface Tree{
size:number
}
let tree: Tree= {
size: 1
}
let f1 = (tree: Tree)=>{
tree.size--
}
function main(){
assert(tree.size === 1)
f1(tree);
assert(tree.size === 0);
}
当我 运行 它时,它在第 20 行编译时给我这个错误:
error: TS2367 [ERROR]: This condition will always return 'false' since the types '1' and '0' have no overlap.
assert(tree.size === 0);
这是有效的断言,但 IDE 和 Typescript 编译器仍然抱怨它。
你是如何解决这个问题的?
正在研究 assert
如何运作 implemented, you can see that it uses assertion signature。
问题是
asserts
ensures that whatever condition is being checked must be true for the remainder of the containing scope.
目前 Typescript 无法知道 f1
modifies/mutates 和 tree
。您可以阅读控制流分析中的权衡 here
作为一种解决方法,您可以防止打字稿为 1
推断文字类型:
assert(tree.size === 1 as number);
这是我在 deno 中 运行 的打字稿代码。
import { assert } from "https://deno.land/std/testing/asserts.ts"
interface Tree{
size:number
}
let tree: Tree= {
size: 1
}
let f1 = (tree: Tree)=>{
tree.size--
}
function main(){
assert(tree.size === 1)
f1(tree);
assert(tree.size === 0);
}
当我 运行 它时,它在第 20 行编译时给我这个错误:
error: TS2367 [ERROR]: This condition will always return 'false' since the types '1' and '0' have no overlap.
assert(tree.size === 0);
这是有效的断言,但 IDE 和 Typescript 编译器仍然抱怨它。 你是如何解决这个问题的?
正在研究 assert
如何运作 implemented, you can see that it uses assertion signature。
问题是
asserts
ensures that whatever condition is being checked must be true for the remainder of the containing scope.
目前 Typescript 无法知道 f1
modifies/mutates 和 tree
。您可以阅读控制流分析中的权衡 here
作为一种解决方法,您可以防止打字稿为 1
推断文字类型:
assert(tree.size === 1 as number);