首页 > 解决方案 > 在 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");

在此处输入图像描述

那么如何拥有安全值呢?我必须通过枚举吗?提前致谢

标签: typescripttypesswitch-statementtype-safety

解决方案


改用泛型,结合将values 映射到返回值的对象:

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;

推荐阅读