Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在typescript中,如何克服由函数修改的值的有效断言测试?_Typescript_Deno - Fatal编程技术网

在typescript中,如何克服由函数修改的值的有效断言测试?

在typescript中,如何克服由函数修改的值的有效断言测试?,typescript,deno,Typescript,Deno,这是我在deno中运行的typescript代码 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

这是我在deno中运行的typescript代码

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
函数是如何使用的

问题是

断言
确保正在检查的任何条件对于包含范围的其余部分都必须为真

目前,Typescript无法知道
f1
修改/变异了
。您可以阅读控制流分析中的权衡


作为一种解决方法,您可以防止typescript推断
1
的文字类型:

assert(tree.size === 1 as number);