2

I'm having a problem properly typing an object key to an enum. This is essentially what I have:

enum ItemTypes {
  WOOD,
  STONE
}

interface Item {
  owned: number,
  max: number
}

const stockpile: {[key in ItemTypes]: Item} = {}

I'm getting an error where stockpile is expecting the itemType enums to already exist within stockpile

Doing this works:

const stockpile: { [key: string]: Item } = {}

However, I would prefer it to be better typed as well as being able to export the enum to be used elsewhere. How would I go about this?

1 Answer 1

2

THere is a big difference between stockpile and stockpile2

const stockpile: {
    [key in ItemTypes]: Item
} = {}

const stockpile2: {
    [key: string]: Item
} = {}

stockpile is and object with up front defined required keys 0 and 1. So, TS forbis you to use empty object when it expects two keys

stockpile2 is just indexed object. It means that there are no required keys/properties, however each key should be a string.

Summary

If you want to make required keys, you should use [key in ItemTypes] otherwise use [key: string]: Item

Hence, if you want to allow only keys from ItemTypes, use :

enum ItemTypes {
    WOOD,
    STONE
}

interface Item {
    owned: number,
    max: number
}

type Stockpile = Partial<Record<ItemTypes, Item>>

const stockpile: Stockpile = {} // ok

const stockpile2: Stockpile = {
    0: { owned: 1, max: 2 }
} // ok

const stockpile3: Stockpile = {
    0: { owned: 1, max: 2 },
    1: { owned: 1, max: 2 }
} // ok

Please keep in mind, that numerical enums are unsafe. Please see my article

Here you can find documentation about utility types: Partial, Record etc ...

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

5 Comments

Hmmm I see. Is there a way to implement what i'm looking for or do you recommend me just using the indexed obj?
Just read ur edit. Guess ill be going with just an indexed obj. Thanks!
@Syn it depends what you want. Do you want to make all keys optional? Then use Partial
@Syn made an update
Interesting. I never used Partials before. This seems really good! I'll need to do further testing but I appreciate the help!

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.