1

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
}

1 Answer 1

4

Got it

type objType = {
  [K in status]: number;
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.