我希望能够在 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
如何让这个示例发挥作用,或者有其他选择吗?
最佳答案
这是一个相当经典的使用 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}`);
}
}
请注意,只有前两个签名是公开的;第三个只是其他代码看不到的实现签名。
关于typescript - 如何将函数参数的类型与某个枚举值关联起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71988777/