简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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