简体   繁体   中英

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM