You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typeApiResponse<Body>={status: 200,body: Body}|{status: number,body: unknown}// Get this type from calling an API...declareconstresponse: ApiResponse<{text: string}>if(response.status===200){response.body.text// this is a string}else{response.body// this is unknown }
Fundamentally, this seems like the type checker needs to evaluate literal types before more general types.
I've also tried using Exclude but that doesnt help for obvious reasons.
This is also useful for strings and string literals too, e.g. {type: "a", a: number} | {type: string, value: unknown}
π» Use Cases
I think its surprisingly common that there are well known types we can use to narrow down a value, while there is still a large unknown amount of types that we aren't aware of an perhaps don't even care about.
The variety of http responses I could get is much larger than I can properly type (unfortunately), but the same can be said for progressively typing a large library. Perhaps I only care about a few different object types, but I still want there to be a catch all for the things I haven't typed yet and might run into...
The text was updated successfully, but these errors were encountered:
You'd need negated types for this to work properly, since this is a legal (but unsound) construction if this were allowed:
constn: number=200;constm={status: n,body: 42};constresponse: ApiResponse<{text: string}>=m;if(response.status===200){response.body.text// claimed as string, but is undefined
Suggestion
π Search Terms
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
π Motivating Example
I want to be able to write code such as
Fundamentally, this seems like the type checker needs to evaluate literal types before more general types.
I've also tried using
Exclude
but that doesnt help for obvious reasons.This is also useful for strings and string literals too, e.g.
{type: "a", a: number} | {type: string, value: unknown}
π» Use Cases
I think its surprisingly common that there are well known types we can use to narrow down a value, while there is still a large unknown amount of types that we aren't aware of an perhaps don't even care about.
The variety of http responses I could get is much larger than I can properly type (unfortunately), but the same can be said for progressively typing a large library. Perhaps I only care about a few different object types, but I still want there to be a catch all for the things I haven't typed yet and might run into...
The text was updated successfully, but these errors were encountered: