0

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

2
  • It's not though, it can be any string, unless you check it explicitly. Maybe make a custom type guard? Commented Jun 6, 2022 at 18:17
  • 1
    What do you mean by "specify"? If you want to assert that it will be, you can use a type assertion to a tuple type like this. But you have to be careful when you use it, since there can be weird edge cases. Is that what you're looking for? If so I could write up an answer; if not, what am I missing? Commented Jun 6, 2022 at 18:26

1 Answer 1

1

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]

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

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.