简体   繁体   English

我可以定义一个枚举和函数的打字稿变量吗?

[英]Can I define a typescript variable that is an enum and a function?

Here is the code so far:这是到目前为止的代码:

function fr(this: any, value: number) {
  return Object.keys(this).find(k => this[k] === value);
}

type getEnumValue = (value: number) => string;
type myEnum = typeof enumVal;

enum enumVal {
  a = 1,
  b = 2
}

let EnumEval = fr.bind(enumVal) as getEnumValue | myEnum;
Object.assign(EnumEval, enumVal);

// Why are the casts required?
console.log((EnumEval as myEnum).a);
console.log((EnumEval as getEnumValue)(1));

console.log(EnumEval as myEnum.a);
console.log(EnumEval(1));

TS errors on the final two lines, requiring me to cast.最后两行出现 TS 错误,需要我进行转换。 Why?为什么?

Playground 操场

Here you go:干得好:

let EnumEval = fr.bind(enumVal) as (((value:number) => string) & (typeof enumVal));

Or:或者:

let EnumEval = fr.bind(enumVal) as (typeof fr & typeof enumVal);

Variable that is an enum and a function - so it should be intersection ( & ), not a union ( | )作为枚举函数的变量- 所以它应该是交集& ),而不是联合|

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM