Asool
Asool

Reputation: 14209

Creating an interface whose keys are values of an enum

Say I have an enum

export enum status {
  PENDING = 'pending',
  SUCCESS = 'success',
  FAIL = 'fail'
}

Assume this enum is used multiple places (i.e, i can't just replace it with something else). However, I do expect other developers to add/delete statuses from it in the future.

Now, I have an object obj, that I want to look like follows

let obj = {
    pending: 10,
    success: 20,
    fail: 0

}

I want to define an interface for the object. I could do something like

interface objInterface = {
   [key: string]: number;
}

however, now someone can set obj to

obj = {
  flip: 3333
}

I don't want that to happen, I only want pending, success, fail, as defined in the enum above.

Ideally, I'd do something like

interface objInterface = {
   [key: TransactionStatus] : number;
}

But that doesn't work - it gives this error:

(parameter) key: TransactionStatus An index signature parameter type cannot be a union type. Consider using a mapped object type instead.ts(1337)

What is the best way of doing this?

I tried

type objType = {
  [K in keyof typeof status]: number;
};

But then when i hover over it, i see that it translates to

type objType = {
  readOnly PENDING: number,
  readOnly SUCCESS: number,
  readOnly FAIL: number
}

Upvotes: 1

Views: 258

Answers (1)

Asool
Asool

Reputation: 14209

Got it

type objType = {
  [K in status]: number;
};

Upvotes: 4

Related Questions