14

In TypeScript, in an array or similar data structure, how can I map a string to an id, while ensuring that only a certain range of ids is allowed?

Here is what I want to do. This works fine. However, I am wondering if there is a more concise way of achieving this?

enum ETypeId {
    alpha  = "a",
    beta   = "b",
    gamma  = "g"
}

interface IType {
    id:     ETypeId,
    title:  string,
}

myTypes: IType[] = [
    { id: ETypeId.alpha, title: "Alpha" },
    { id: ETypeId.beta,  title: "Beta"  },
    { id: ETypeId.gamma, title: "Gamma" }
];

As is, I have to do the following to get from the id to the title:

function getTypeForTypeId( typeId: ETypeId ): IType {
    return myTypes.find( type => type.id == typeId );
}

Can I use a different data structure that makes some of the above code more concise, or is this already as good as it gets?


Explanation:

  • "a" is what gets stored in my database
  • ETypeId.alpha is how I access it in my code
  • "Alpha" is what gets displayed to the user.

2 Answers 2

14

Agree with Sergi Dote Teixidor's answer that Map is the best option for such problem. However, based on the described problem, I think that it could be simplified to Map<ETypeId, string>:

enum ETypeId {
    alpha  = "a",
    beta   = "b"
}

const types: Map<ETypeId, string> = new Map( [
   [ ETypeId.alpha, "Alpha" ],
   [ ETypeId.beta, "Beta" ],
]);

Just in case you want to initialize your structure once and make TypeScript protect you from changing values inside your map:

enum ETypeId {
    alpha  = "a",
    beta   = "b"
}

interface ReadonlyMap<TKey, TValue> {
    get(key: TKey):TValue;
}

const types: ReadonlyMap<ETypeId, string> = new Map( [
   [ ETypeId.alpha, "Alpha" ],
   [ ETypeId.beta, "Beta" ],
]);

// Static analyzer error if you try to change the value:
types.set(ETypeId.alpha, "NewValue");
Sign up to request clarification or add additional context in comments.

Comments

11

you can use a map:

  1. you can retrieve directly any element
  2. you can loop all elements if you want

example:

enum ETypeId {
    alpha  = "a",
    beta   = "b",
    gamma  = "g"
}

interface IType {
    id:     ETypeId,
    title:  string,
}

const myMap: Map<string, IType> = new Map( [
   [ ETypeId.alpha,  { id: ETypeId.alpha, title: "Alpha" } ],
   [ ETypeId.beta,  { id: ETypeId.beta,  title: "Beta"  } ],
   [ ETypeId.gamma, { id: ETypeId.gamma, title: "Gamma" } ]
]);

console.log(myMap.get(ETypeId.alpha)) // -> {id: "a", title: "Alpha"}

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.