I am facing an issue with this script:
type Input = string
function util(input: Input) {
return input
}
function main(input: Input | null) {
const isNull = input === null
if (isNull) {
return 'empty string'
}
input = util(input) //error
}
The error message reads:
Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'
Interestingly, the error does not occur when:
- The last line is
return util(input)
- The conditional statement is shortened to
if (input === null)
Why is that happening?
The reason I avoided a direct check for null value in the condition clause is because I needed to test for both null and match against a regex pattern. Since regex.test(value) returns true when logged but false within an if statement, I decided to combine both checks in a single variable for convenience. This method:
const isNullOrEmpty = input === null || /^\\s+$/.test(input)
if (isNullOrEmpty)
is more convenient than:
const isEmpty = /^\\s+$/.test(input)
if (input === null || isEmpty)