javascript - TypeScript - TS2322: Type 'string' is not assignable to type '"str1" | "str2"'
问题描述
I have a function that, can accept only two possible values (for validation). For this I do:
interface PossibleValues {
key: "str1" | "str2";
}
I can call the function with a string type only. This is by our architectural design and I have to deal with it.
set({key: type})
Because type
is string and key
can accept only "str1" | "str2"
it says:
TS2322: Type 'string' is not assignable to type '"str1" | "str2"' which makes sense.
The question is how to overcome this in a most elegant way? I mean I want to pass a string but the function call should fail if the string is not one of the two "str1" | "str2"
What I tried to do is:
set({key: type} as PossibleValues)
and it stopped complaining but the desired behavior is not achieved. If I pass "str333" for example it still works.
Any ideas?
解决方案
您需要意识到 TypeScript 只是为了帮助您解决编译时错误。它对运行时没有任何作用,因为它被编译为 JavaScript。类型和接口不存在。
话虽如此,除非您对字符串进行硬编码以传递给这个函数,否则您str1 | str2
不应该依赖 TypeScript 类型来确保它工作。
您需要编写 JavaScript 检查代码并允许将任何字符串传递给函数。
你可以创建一个类型保护来实现这个效果。
function isKey(value: string): value is "str1" | "str2" {
return value === "str1" || value === "str2";
}
然后,你可以用它告诉 TypeScript 你已经检查了类型。
if(isKey(type)) {
set({ key: type }); // typescript won't complain anymore because you did a type check
}
推荐阅读
- ios - 无法本地化不匹配人脸的人脸 ID 弹出窗口
- shopify - 在 Shopify 中堆叠折扣代码
- algorithm - 在最小堆中找到第 7 个最小的元素
- numpy - Tensorflow 矩阵乘法比 numpy 慢
- php - Mysql从2个表中的2列完全搜索
- reinforced-typings - 如何在不创建无效导入的情况下引用外部库类型
- python-3.x - 如何使用 python 脚本将用户在我的网站上上传的文件存储到 azure 上?
- r - 如何在 R 中使用 smotefamily 处理分类变量?
- javascript - CryptoJS 说 Crytpo.js 文件未找到错误
- oracle-sqldeveloper - sqldeveloper 加载数据库内容的时间太长