Repository navigation
Open
Labels
Description
Suggestion
🔍 Search Terms
Type guard, parent object, infer, inference
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
Typescript should be able to infer the type of an object, if a type guard was checked on a property of the said object. Currently, Typescript does correctly infer the type of the property, but not its parent object.
📃 Motivating Example
The following example is very common in data oriented design.
interface Type1 { list: string[] }
interface Type2 { list: { [key: string]: string } }
declare const obj: Type1 | Type2;
if(Array.isArray(obj.list)) {
const list: string[] = obj.list; // WORKS
const map: { [key: string]: string } = obj.list; // ERROR, as expected
const objCasted: Type1 = obj; // ERROR, unexpectedly
} else {
const map: { [key: string]: string } = obj.list; // WORKS
const list: string[] = obj.list; // ERROR, as expected
const objCasted: Type2 = obj; // ERROR, unexpectedly
}The following example works and that is good because it is an equally common case in this type of design.
interface Type3 { type: 'type3', data: boolean }
interface Type4 { type: 'type4', data: string }
declare const obj2: Type3 | Type4;
if(obj2.type === 'type3') {
const objCasted: Type3 = obj2; // WORKS
} else {
const objCasted: Type4 = obj2; // WORKS
}So I believe the type guards should work the same way. As far as I see, this does not cause any inconsistency in the language or the type system. It is an improvement without any downsides.
💻 Use Cases
See the full example.
Reacted by Matt, Joe Calzaretta, DetachHead, bartenra, Sindre Sorhus, Marc Fallows, George, Alasdair McLeay, Scott Sidwell, Matt Kantor and 131 more
Reacted by lionel-rowe and Ellie
Activity
MartinJohns commentedon Jan 17, 2021
Quoting @jack-williams:
Used search terms:
type guard property parentgkurt commentedon Jan 18, 2021
Martin Johns (@MartinJohns) Thanks but I am trying to understand why. Consider this example:
So if I check with
obj3.type === true, it narrows the type of the parent correctly. So thetypeproperty is correctly detected as a discriminator property. But type guards don't narrow the the of the parent and that is by choice. Is that because of performance concerns? Type guard seems like a more exhaustive mechanism than simple equality check. I would expect it to be easier to implement.RyanCavanaugh commentedon Jan 19, 2021
I want to take another look at this; seems like we might have the right machinery in place now
JoshuaWise commentedon Mar 26, 2021
I ran into this issue today, and would love to see it resolved. In my case, I'm using the excellent SuperStruct package to validate parts of an incoming HTTP request in Koa. I'm using the type guards generated by SuperStruct to validate the query parameters (
ctx.query) and request body (ctx.request.body). However, the parentctxobject is not affected by these type guards, so I can't pass thectxto a type-safe handler (e.g., a handler that expects thectx.request.bodyto match a certain schema).bartenra commentedon Jul 2, 2021
I ran into a similar situation today, which boiled down to (see duplicated issue):
dospunk commentedon Jan 27, 2022
I've run into this issue too. anyone found a work-around yet? I'd really like to not have to repeat type guards all over the place
ddejohn commentedon Feb 11, 2022
Also having this issue. See this playground.
bartenra commentedon Mar 30, 2022
Here is a workaround for my use case:
Playground
Fryuni commentedon Sep 6, 2022
I mentioned another workaround on a duplicate issue that I opened, so just sharing it here.
For simple use cases, like checking if a single value is defined or not, there is no need to add a type guard since that would make an extra function call in runtime. Wrap the type and the property here to make it propagate:
This makes transforms a record with an optional property into a union using the presence of that property as the discriminator.
Example on the playground.
jcalz commentedon Oct 13, 2022
This is mentioned in #50891 already linked here, but for visibility:
Now that
in-narrowing for unlisted properties is a thing, the suggestion here would be very useful to support runtime type checking of the formif ((x) && (typeof x === "object") && ("foo" in x) && (typeof x.foo === "string") & ...medihack commentedon Oct 20, 2022
Another minimal example (Playground) which demonstrates the problem. Makes it quite hard to work with complex typed objects.
jcalz commentedon Oct 25, 2022
Cross-linking #18758 which asks for nested discriminated unions (I imagine this feature would automatically enable that one?)
nmattia commentedon Feb 3, 2023
Hi, I was about to create a ticket for something similar and I think this would be a duplicate of this issue. Can you confirm?
Output
Compiler Options
{ "compilerOptions": { "strict": true, "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictPropertyInitialization": true, "strictBindCallApply": true, "noImplicitThis": true, "noImplicitReturns": true, "alwaysStrict": true, "esModuleInterop": true, "declaration": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "target": "ES2017", "jsx": "react", "module": "ESNext", "moduleResolution": "node" } }Playground Link: Provided
Fryuni commentedon Feb 3, 2023
Seems like the same issue Nicolas Mattia (@nmattia).
Just as a point for this particular example, if the type were a union of objects with distinct types, it would narrow it down to the correct alternative, that is how tagged unions work after all. The narrowing doesn't work if the union is on the field, or if it is narrowing a field from a non-literal type to a literal type (
numberto0in this case)So this works, but this doesn't.
I sent a workaround here on #42384 (comment) for narrowing between multiple non-literal types (
string | undefinedin the example) by converting a record with a union field into a tagged union of records each with a different type for the field. It might be possible to do the same for narrowingnumberto a literal, but I haven't tried that yet.gordonmleigh commentedon Feb 22, 2023
The simplest workaround I figured out is:
Then narrowing works as expected if you use
hasPropertyto check the existence of a property.jtbandes commentedon Nov 9, 2023
Ryan Cavanaugh (@RyanCavanaugh) any chance this improvement could still be achievable in the hopefully-not-too-distant future? 🙂
DawidKopys commentedon Jun 13, 2024
I have another reproduction but I am not entirely certain this is the same issue - here.
jcready commentedon Jul 5, 2024
Just sharing another use-case which is for interfaces we don't control. For example the GeoJSON spec was created years before TypeScript existed. Working with GeoJSON in TypeScript is rather painful as typically the types are something like:
It's simply not possible to refine a
FeaturetoFeature<Polygon>, but various libraries (that existed before TypeScript) that only takeFeature<Polygon>and all I have is aFeature.MichalMarsalek commentedon Aug 26, 2024
Naturally it's less convenient than if this issue was implemented, but it's usually not too bad to write a sort of typeguard factory for cases like this.
Also this usecase doesn't really need the full generality of this issue, something like #18758 would suffice.
AlbertMarashi commentedon Sep 4, 2024
mmm having to end up doing a lot of type assertions to handle this...
I ended up creating a type guard in case anyone wanted some inspiration or an example
Rudxain commentedon Nov 14, 2024
Another repro, using
Array#everyas a workaround (inefficient). However, it has the caveat that a re-assignment/re-declaration must happen inside the branch, to allow CFA to narrow the destructuring patterneliasm307 commentedon Dec 24, 2024
I've run into a similar issue also regarding whether properties of an object are non-nullable, see example below:
See https://www.typescriptlang.org/play/?#code/MYewdgzgLgBCBGArAXDA3gMxCV0BOAlmAOYwA+MYArgDY0C+MAvOljjAEQf0DcAUHwAmAU2A0AhnmEwMVMMCgFwMgBSTiqTNlxRCJegEpUANxAFBAghhUJEAOjYH0fGK9W2nAek8wAKgE0ABQBRGGCAJXCAeXDUEGNhPHE6OCRRWCgATwAHaTAQWDBJPBAAd2FBGCgQGAALcQSYbJLcvCyYcQhKcABaajpxeBphATdVLXZbB2xDGG8YKIBpOLSFJpbE9qzcrqK8EvLK0trhMBgqCAqYIkECY3MqZJpMvnogA
lith-x commentedon Apr 24, 2026
Another snippet I made trying to hone in on what was going on before I found this issue. I'll post it here, maybe someone will find it clarifying. Hopefully this will get revisited once TS7 work finishes up :)