Skip to content

Property 'groups' does not exist on type 'RegExpExecArray | null' when I have set esnext in lib of tsconfig.json #35604

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
liudonghua123 opened this issue Dec 10, 2019 · 4 comments

Comments

@liudonghua123
Copy link

TypeScript Version: 3.7.3

Search Terms:

Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
const pageInfo = `page: 1/12 total: 234 `
const {
  groups: { totalPage, count },
} = /page1\/(?<totalPage>\d+).* total(?<count>\d+) /.exec(pageInfo);
console.info({ totalPage, count })

tsconfig.json

{
  "compilerOptions": {
    // Target latest version of ECMAScript.
    "target": "esnext",
    // Search under node_modules for non-relative imports.
    "moduleResolution": "node",
    // Process & infer types from .js files.
    "allowJs": true,
    // Don't emit; allow Babel to transform files.
    "noEmit": true,
    // Enable strictest settings like strictNullChecks & noImplicitAny.
    "strict": true,
    // Disallow features that require cross-file information for emit.
    "isolatedModules": true,
    // Import non-ES modules as default imports.
    "esModuleInterop": true,
    // https://www.detroitlabs.com/blog/2018/02/28/adding-custom-type-definitions-to-a-third-party-library/
    "typeRoots": [
      "./@types",
      "./node_modules/@types"
    ],
    "lib": [
      "esnext",
      "es2018.regexp"
    ],
  },
  "include": [
    "src",
    "tools"
  ]
}

Expected behavior:
When run tsc, No error or warning shown

Actual behavior:
error TS2339: Property 'groups' does not exist on type 'RegExpExecArray | null'.

Playground Link:
http://www.typescriptlang.org/play/?target=99&ssl=1&ssc=1&pln=5&pc=35#

Related Issues:
#22082

@MartinJohns
Copy link
Contributor

Everything works as intended.

exec() returns the union type RegExpExecArray | null. When you have a union type you can only access properties that are present on all types, and null does not have a groups property. When you narrow the type with a type-check for null you can access the groups property.

Following that, the groups property is an indexer, it doesn't has explicit totalPage and count properties. This would require #32098.

@liudonghua123
Copy link
Author

@MartinJohns Thank you very much. Now I understand it. 😃

@ahmadxgani
Copy link

@liudonghua123 may i know how do you solve it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants