I can't imagine this question hasn't been asked already, but I can't find it. That may have something to do with not knowing what keywords to search for that describe my question.
Anyway, let's say we have this Typescript:
const value = undefined
const doSomethingWithValue = (value: number) => console.log(value)
const isDefined = (value?: unknown) => value != null
if (value != null) {
doSomethingWithValue(value) // Works great!
}
if (isDefined(value)) {
doSomethingWithValue(value) // Boo, error!: Argument of type 'undefined' is not assignable to parameter of type 'number'.
}
As you can see, the isDefined
function checks for null
/undefined
, but Typescript can't seem to figure it out like it does when using the explicit check in the if
statement. I know I can add a type hint like so:
if (isDefined(value)) {
doSomethingWithValue(value as unknown as number) // Works, but "eh"
}
Which is okay, I suppose - definitely not ideal. Is there not a better way?
EDIT: Non-null assertion operator
So, I just learned I can use the "Non-null assertion operator" like so, but it's still not "great":
if (isDefined(value)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
doSomethingWithValue(value!) // Works, not ideal still...
}
That works, but requires disabling the eslint rule @typescript-eslint/no-non-null-assertion
: https://github.com/typescript-eslint/typescript-eslint/blob/v5.1.0/packages/eslint-plugin/docs/rules/no-non-null-assertion.md, where the docs warn: "Using non-null assertions cancels the benefits of the strict null-checking mode." and "If you don't care about strict null-checking, then you will not need this rule."
But, I do care about strict null checking! I don't want to disable that entirely