0

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

2
  • 1
    Can you tell me what is your motivation to use enum in such way? Enum should be used as enum, so just simple variant. Commented Jan 28, 2020 at 12:35
  • @MaciejSikora a non TS user was saying that TS couldn't handle this typing, and I was having trouble actually showing the user that it could. Since the primary purpose of this code is to be able to get a text value or int value from the same object I did let them know that Enums in TS already solve this for you in a way simpler way. Commented Feb 2, 2020 at 18:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.