typescript - 在 Typescript 中使用 switch 获取函数的安全值
问题描述
我有一个函数,它接受一个可以有 3 个不同值的参数。这个函数根据参数返回一个值,所以它可以返回三个不同的值。
所以我使用了一个开关,它比较参数以确定要返回的值。所以我对参数的每个可能值都有一个安全值。
但是,如果我使用参数调用函数,则返回值不确定,TypeScript 保留其他 2 个值的可能性。
function get(value: "string" | "number" | "boolean") {
switch (value) {
case "string":
return "A";
case "number":
return 1;
case "boolean":
return true;
}
}
var test1 = get("number");
那么如何拥有安全值呢?我必须通过枚举吗?提前致谢
解决方案
改用泛型,结合将value
s 映射到返回值的对象:
const map = {
string: 'A',
number: 1,
boolean: true,
};
type MapType = typeof map;
function get<T extends keyof MapType>(value: T) {
return map[value];
}
var test1 = get("number");
如果您希望返回类型准确- 例如不仅仅是number
,而是1
- 然后声明地图as const
以避免自动扩大:
const map = {
string: 'A',
number: 1,
boolean: true,
} as const;
推荐阅读
- sql - oracle 是否支持 stftime() 函数?
- javascript - 如何使用 moment.js 将日期格式化为 ISO 日期(mongodb)?
- sql - 如果记录存在,我可以更新它,如果不存在,我可以在 SQL Server 的单个查询中为多行插入它吗?
- java - Jmeter - 使用 HTTP 请求在 Jmeter 中构造 URL
- r - 将特定行转换为 R 中的新列
- sql - 如何将 Oracle SQL 中的存储过程从一个模式移动到另一个模式?
- javascript - 如何使用 Nextjs 显示 mp4 文件格式?
- callback - 在 Slack 中传递没有附件的 callback_id
- angular - 动态改变显示的角度子组件
- python - 在 docker 上部署一个 REACT 和 Flask 应用程序