Home > front end >  how to specify type of array element in typescript?
how to specify type of array element in typescript?

Time:06-07

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)?

CodePudding user response:

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]

  • Related