Typescript: Regexp.test incorrectly rejects null value as input

Created on 17 Apr 2019  路  4Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.2.4


Search Terms: RegExp.test null strict

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 reg = /someRegexHere/;
console.log(reg.test(null)); // correctly returns false but typescript doesn't let null

Expected behavior:
null is perfectly fine to pass into test method of RegExp, and typescript should not complain on that.
Actual behavior:
Typescript doesn't allow null values (when StrictNullChecks is on obviously)
Playground Link:

Related Issues:
This issue is almost an exact duplicate of this: https://github.com/Microsoft/TypeScript/issues/20501
But it's locked, so I couldn't comment on that.

IMPORTANT:
Please note that @styfle argument about not accepting null or undefined, is correct only for undefined, and not for null.

Working as Intended

Most helpful comment

I have no idea what "perfectly fine" is supposed to mean here. Converting null to its string representation "null" is almost always a mistake and is going to subject you to crazy false positives like the one shown above.

All 4 comments

It depends on your regex.

Imagine this use case for matching html list items.

const reg = /(ul|li)/;
console.log(reg.test(null)); // true

If you really want to tell TS that you don't care about null or undefined, use String()

const reg = /someRegexHere/;
console.log(reg.test(String(null)));

I have no idea what "perfectly fine" is supposed to mean here. Converting null to its string representation "null" is almost always a mistake and is going to subject you to crazy false positives like the one shown above.

@RyanCavanaugh @styfle
You are right. I rushed into creating an issue without paying attention to how .test() treats null and undefined. Sorry about that.

I didn't know what it did until I tried it either 馃槄

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MartynasZilinskas picture MartynasZilinskas  路  3Comments

weswigham picture weswigham  路  3Comments

jbondc picture jbondc  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments