Search Terms
type check
array
union
Suggestion
If we define a type like [null, string] | [number, null], we know that, if the first element is null, the second element is string, and if the second element is null, the first element is number. But, the type check can't understand it, what is less accurate than desired.
Use Cases/Example
When we creating a new function, we could want to return a value that is returned in success case, or an error if it failed. A simple way to do it is using an array, for example:
const createUser = (): [User, null] | [null, Error] => {
...
Then, this function can return [User, null] or [null, Error]. But, the type check can't work very well:
const [user, error] = createUser()
if (user === null) {
console.log(error.message) // type check mark a warning where,
// saying that "error" could be null, but it is impossible!
return
}
// type check say that "user" never will be null. It is ok.
or...
const [user, error] = createUser()
if (error !== null) {
console.log(error.message) // no warning
return
}
// type check say that "user" could be null, but it is impossible
Search Terms
type check
array
union
Suggestion
If we define a type like
[null, string] | [number, null], we know that, if the first element isnull, the second element isstring, and if the second element isnull, the first element isnumber. But, the type check can't understand it, what is less accurate than desired.Use Cases/Example
When we creating a new function, we could want to return a value that is returned in success case, or an error if it failed. A simple way to do it is using an array, for example:
Then, this function can return
[User, null]or[null, Error]. But, the type check can't work very well:or...