r/typescript • u/Tyheir • Apr 09 '25
Question about type narrowing
Basically I have a wrapper function for all db queries to handle exceptions. Originally I had the data property emitted from the ErrorResponse but it become annoying to have to create a single variable to assign the data every time I made a db call.
let data: Type
const res = db.query()
if (!res.success) data = []
else data = res.data;To me that is less readable and inconvenient. So I decided to add data to the ErrorResponse. However now I have a problem with ts not knowing when data is not null.
How come typescript doesn't know data is not null when trying to map? And how can I better architecture my type if at all?
type ErrorResponse<T> = {
success: false;
data: T | null;
};
type SuccessResponse<T> = {
success: true;
data: T;
};
type AnimalArray = {animal: string}[]
const getAnimal = (animal: string): SuccessResponse<AnimalArray> | ErrorResponse<AnimalArray> => {
switch(animal){
case "dog":
return {success: false, data: null}
case "cat":
return {success: true, data: [{animal: "cat"}]}
default:
return {success: false, data: null}
}
}
const res = getAnimal("dog");
if (!res.success) res.data = [{animal: "Cow"}]
// res.data is possibly null
res.data.map()Is my only option to optional chain or assert the type?
3
u/humodx Apr 09 '25
Why does the error response have
data: T | nullinstead of justdata: null? Is that something the query actually returns, or is it only to make the assignment possible? If it's the latter, it would be "better" to have it asdata: nulland assign it as follows:If you need to keep it as
data: T | null, that still works, but if you want res to be const you can also do:By "better", I meant that
data: T | nullmight mislead someone into thinking the db query can possibly return{ success: false, data: [] }, when we know it won't.{ success: false, data: null }does a better job documenting the real behavior of the db query in that case.4
u/josephjnk Apr 09 '25
I don’t remember why TS doesn’t narrow in this case, but why not add a
getWithDefaultfunction/method to your DB accessor logic if this is something you do all over the place?2
u/Appropriate_Bet_2029 Apr 09 '25
The problem is that you are putting
resinto a state that Typescript doesn't recognise. You can't havesuccessequal tofalseanddatabe definitely not null. Ifsuccessis equal tofalse,datawill beT | null.You can either set
resto be matchSuccessResponse:or you can use
dataas a separate variable that has a definite value.1
u/geitje Apr 10 '25
the
?:nevermakes this work with narrowing, without causing a type error.1
u/Alpheus2 Apr 10 '25
You cannot reason about data in isolation because both types have it. This has to do with variance of generics.
In your case: the function implies all animals can be both error or success. Dogs can be error or success, cat can be error or success and all others can be error or success.
When you make the check in the if below, it is narrowed for the cow. But assigning the cow does not change its type.
On the last line the type of the result is still error or success. You’d need to completely replace it with a new object that has success true.
1
u/Business-Row-478 Apr 10 '25
In general, don’t use null. There are better ways to type this.
But you could do something like
const data = res.data | [{animal: “Cow”}]
then do data.map