Home > other >  What is the typescript type for the return value of String.prototype.match()?
What is the typescript type for the return value of String.prototype.match()?

Time:01-10

I am writing a regex in javascript

const pattern = /S(\d )E(\d )/; // get characters inbetween "S" and "D"
const result  = 'SE01E09'.match(pattern);

how do i type the result variable?

I have tried a couple of different approaches such as the following to no avail

const result: Array<string | number>  = 'SE01E09'.match(pattern);

CodePudding user response:

You should learn how to answer that yourself: you can at any time hover over a value in your IDE and see the inferred type in a tooltip. Here it would be: RegExpMatchArray | null.

Then you can go to the definition, for example by Alt clicking it (it will depend on your IDE). You may need to type it down so that the link is available (in VS Code, no way to Alt click the tooltip itself), for example:

type R =  RegExpMatchArray;
//        ---------------- now you can Alt   click this

Here there are two definitions:

// from lib.es5.d.ts
interface RegExpMatchArray extends Array<string> {
    /**
     * The index of the search at which the result was found.
     */
    index?: number;
    /**
     * A copy of the search string.
     */
    input?: string;
    /**
     * The first match. This will always be present because `null` will be returned if there are no matches.
     */
    0: string;
}

// from lib.es2018.regexp.d.ts
interface RegExpMatchArray {
    groups?: {
        [key: string]: string
    }
}

Because of a feature called interface merging, you can expect RegExpMatchArray to have both behaviours.

Now you should be able to look up anything.

CodePudding user response:

It would be RegExpMatchArray | null .

const result: RegExpMatchArray  | null  = 'SE01E09'.match(pattern);

More details can be found here

  • Related