Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to specify type of array element in typescript?

I have this code:

enum MyValues  {
    FIRST = "firstValue",
    SECOND = "secondValue",
};

type myObjectType = {
    myKey: string;
    myValue: MyValues;
}

const tags: string = "someKey:firstValue";

const parseTags = (tags: string): myObjectType => {
    const [myKey, myValue] = tags.split(":");  /// ???
    return {
        myKey,
        myValue, ///???
    }
};

console.log(parseTags(tags))

How to specify, that first array element is string, but second one is enum (MyValues)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you just want to give it that type, you can add as [string, MyValues] after tags.split(":").

As @decorator-factory points out in their comment, this will not actually check that the result of tags.split(":") actually matches that type:

  • If tags doesn’t contain ':', you will get only one array element and the destructuring will fail.
  • If the second element doesn’t match the enum, you won’t get an error at that point, but you may get one later on when you try to use the value. (This could be harder to debug later.)

The "type guard" concept mentioned by @decorator-factory is explained here. Basically it’s a function that checks the actual type of a value and is annotated in a way that allows TypeScript to infer what the type will be if the function returns true. For example, you could create a type guard to check that a given value is an array with exactly two elements, and the second element is one of the possible values of the MyValues enum. The annotation for that type guard would look like : value is [string, MyValues]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading