Skip to content

Unhandled error when computing local module specifier #37731

@devversion

Description

@devversion

TypeScript Version: 3.8.3

Search Terms:

  • TypeError: Cannot read property 'lastIndexOf' of undefined
  • getPathRelativeToRootDirs throws due to missing undefined guard.
  • Type Checker throws if non-existent symbols are resolved, but rootDirs are not absolute.

Code

An easy reproduction can be found here: https://github.com/devversion/ts-checker-root-dir-runtime-exception.

Steps:

  1. Clone the repo
  2. Run yarn
  3. Run node ./test.js.
  4. Check the console output for the exception:
TypeError: Cannot read property 'lastIndexOf' of undefined
    at Object.startsWith (<..>\node_modules\typescript\lib\typescript.js:2044:20)
    at isPathRelativeToParent (<..>\node_modules\typescript\lib\typescript.js:102733:23)
    at <..>/node_modules\typescript\lib\typescript.js:102692:24
    at Object.firstDefined (<..>\node_modules\typescript\lib\typescript.js:347:26)
    at getPathRelativeToRootDirs (<..>\node_modules\typescript\lib\typescript.js:102690:23)

Explanation on what is happening:

Currently when developers parse a tsconfig using ts.parseJsonConfigFileContent, a base path needs to be specified. If that base path is not an absolute file path, the type checker can fail
down the road when it tries to compute relative paths based on rootDirs.

This can be observed when the relative tsconfig path is made absolute in the test.js file. At this point, the type checker will not throw, and getSymbolAtLocation works as expected.

Expected behavior:

Calling typeChecker.getSymbolAtLocation (as seen in test.js) should never cause a runtime exception. Hence getPathRelativeToRootDirs should be updated to catch cases where the relative path cannot be computed (i.e. undefined is returned).

Similarly, I'd expect ts.parseJsonConfigFileContent() to either throw if no absolute base path is specified, or expect the path to be resolved based on the CWD. Not sure if that makes sense though.

Actual behavior:

It throws with a runtime exception. See error snippet above. The error surfaces because no relative path can be computed in getPathRelativeToRootDirs. This is because (as explained above), the root directories are not absolute paths, and getPathRelativeToRootDirs does not guard against undefined being returned from getRelativePathIfInDirectory.

Related Issues:

Metadata

Metadata

Assignees

Labels

Working as IntendedThe behavior described is the intended behavior; this is not a bug

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions