gpt4 book ai didi

typescript - Typescript是否允许将 “any”分配给其他所有类型?如何处理渔获(错误: any)?

转载 作者:行者123 更新时间:2023-12-03 08:17:42 24 4
gpt4 key购买 nike

我记得在文档中读到,所有类型都可以分配给any。但是我不记得阅读过any可分配给其他所有类型。

function takesAString(x: string) {
console.log(x);
}

const xAny: any = {}

takesAString(xAny); // <--- WHY IS THIS NOT AN ERROR ?
takesAString(true);
takesAString(111);
enter image description here
我在 try-catch循环中遇到了这个麻烦:
catch(err) {                    // TYPESCRIPT EVALUATES err AS any
dispatch(SOME_ACTION(err)); // THIS EXPECTS err TO BE OF TYPE STRING
}
Typescript隐式将catch块 err参数评估为 any,并且没有给我任何提示 SOME_ACTION(err)可能没有获得预期的 string
这是正常行为吗?怎么处理呢?

最佳答案

这不是错误,因为any特别是选择了类型检查的。从the documentation:

Any

In some situations, not all type information is available or its declaration would take an inappropriate amount of effort. These may occur for values from code that has been written without TypeScript or a 3rd party library. In these cases, we might want to opt-out of type checking. To do so, we label these values with the any type ...


(我的重点)
将此与 unknown type(我认为是相对较新的)进行对比,您在代码中标记的行确实是一个错误:
const xUnknown: unknown = {}

takesAString(xUnknown); // <--- This is an error
Playground link

关于typescript - Typescript是否允许将 “any”分配给其他所有类型?如何处理渔获(错误: any)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64159526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com