typescript - 如何将函数参数的类型与某个枚举值关联起来?

标签 typescript enums closures

我希望能够在 TypeScript 中编译时关联枚举和类型。

目标是用枚举修复方法的参数。我尝试用闭包来做到这一点:

enum EnumType {
    TYPE1,
    TYPE2
}

interface Type1 {
    name: string;
}

interface Type2 {
    value: number;
}


function closure(tEnum: EnumType) {
    switch(tEnum){
        case EnumType.TYPE1: 
        return (t: Type1) => { console.log(t); }
        case EnumType.TYPE2: 
        return (t: Type2) => { console.log(t); }
    }
}

const foo1 = closure(EnumType.TYPE1);
foo1({ name: 'test'}); // here no error Type1 (but there is an error)
foo1({ value: 2}); // here error because not Type1

Playground

如何让这个示例发挥作用,或者有其他选择吗?

最佳答案

这是一个相当经典的使用 function overloads 的地方:

function closure(tEnum: EnumType.TYPE1): (arg: Type1) => void;
function closure(tEnum: EnumType.TYPE2): (arg: Type2) => void;
function closure(tEnum: EnumType) {
    switch(tEnum){
        case EnumType.TYPE1: 
            return (t: Type1) => { console.log(t); }
        case EnumType.TYPE2: 
            return (t: Type2) => { console.log(t); }
        default:
            throw new Error(`Invalid enum value ${tEnum}`);
    }
}

Playground link

请注意,只有前两个签名是公开的;第三个只是其他代码看不到的实现签名。

关于typescript - 如何将函数参数的类型与某个枚举值关联起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71988777/

相关文章:

c# - 可以将 C# 枚举声明为 bool 类型吗?

lambda - lambda 函数的类型是什么?

html - Chartjs 和 Angular 5 上的错误 - "can' t 从给定项目获取上下文”

javascript - Angular 4 Reactive Forms FormControl错误为空

angular - Typescript中的字符串插值,用变量替换 'placeholders'

java - Java 中枚举的命名 : Singular or Plural?

typescript - Webpack worker-loader 无法编译 typescript worker

c# - 枚举到 int 最佳实践

Javascript 闭包——它们之间有什么区别

Javascript 闭包和前置后函数处理程序