2

I have the following method which transforms a string instance of an enum to the corresponding enum member on an object:

function transformEnum<TBase>(base: TBase, member: keyof TBase, enumInstance: any) {
    base[member] = enumInstance[base[member]];
}

It's called like this:

transformEnum(result, "day", DayOfWeek);

Is there any way to type the enumInstance variable? The typing doesn't have to be perfect, but constraining it at least somewhat would be nice.

Alternatively I've tried

function transform<T>(get: () => T, set: (x: T) => void, enumInstance: T) {
    set((enumInstance as any)[get()]);
}

But when I call this like so:

transform<DayOfWeek>(() => result.day, (x) => { result.day = x; }, DayOfWeek);

I get

[ts] Argument of type 'typeof DayOfWeek' is not assignable to parameter of type 'DayOfWeek'.

2
  • Please check if this works for you : stackoverflow.com/questions/17380845/… Commented Mar 27, 2017 at 9:33
  • @BalajiV if you read my code sample you'll see that that's what I'm doing. The question isn't how to do the conversion but how to type the function parameter. Commented Mar 27, 2017 at 9:35

1 Answer 1

3
function transform<T, TKey extends keyof T>(get: () => TKey, set: (x: T[TKey]) => void, enumInstance: T) {
  set(enumInstance[get()]);
}

Example:

enum DayOfWeek {
    Monday, Tuesday, Wednesday, ...
}

type DayOfWeekKey = keyof typeof DayOfWeek;

class ClassWithDay {
  day: DayOfWeekKey | DayOfWeek;
}

let c = new ClassWithDay();
c.day = "Monday";
transform(() => c.day as DayOfWeekKey, v => {c.day = v;}, DayOfWeek);
// c.day is now 0
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.