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
{{ message }}
Repository navigation
Optional chaining of unknown should be unknown #37700
Currently it is forbidden to use optional chaining on unknown. But for all possible types in JavaScript, optional chaining will return undefined if it does not apply or cannot find the field. So we should safely regard optional chaining of unknown type to be unknown as well.
This is the verification of optional chaining on all possible types in JavaScript:
Currently we will need to cast explicitly on someUnknown, someUnknown.fieldA, someUnknown.fieldA.fieldB and someUnknown.fieldA.fieldB.fieldC. People will find this is unnecessary verbose and may just fallback to use any.
Examples
As above
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, etc.)
This is as safe as allowing property access on {} (unknown is pretty much the same as {} | null | undefined) or allowing access to unknown properties in interfaces in general.
I don't think you should be able to do something with a type and not with its sub-types (we already have any for these things).
And if this would be allowed, why should it be restricted to the optional chaining syntax?
I think the real weirdness is that it'd break the operational directionality of unknown. Normally for any type S that's a subtype of T, if an operation is allowed on T then it's definitely allowed on S, but now unk?.prop is valid when e.g. ({ x: 1 })?.prop isn't even though { x: 1 } is by definition a subtype of unknown.
This would lead to some subtle breakage in the future, e.g. let's say you wrote
The proposal is to make this code OK, but then in the future it'd be a breaking change for us to narrow x to { y: unknown } in the body of the if, which seems bad - narrowing should only ever increase the set of things you're allowed to do.
Reacted by Eric S. Rogstad, Daniel Rosenwasser, ExE Boss and Chiawen Chen
I think the real weirdness is that it'd break the operational directionality of unknown. Normally for any type S that's a subtype of T, if an operation is allowed on T then it's definitely allowed on S, but now unk?.prop is valid when e.g. ({ x: 1 })?.prop isn't even though { x: 1 } is by definition a subtype of unknown.
This would lead to some subtle breakage in the future, e.g. let's say you wrote
The proposal is to make this code OK, but then in the future it'd be a breaking change for us to narrow x to { y: unknown } in the body of the if, which seems bad - narrowing should only ever increase the set of things you're allowed to do.
Hi Ryan thank you for your excellent example. I agree that narrowing should only ever increase the set of things that are allowed to do. But I can think of a counterexample involving the use of contravariance.
interface Action {
actionType: string;
}
interface KeyboardAction {
actionType: 'keyboard';
key: string;
}
let genericHandler: (payload: Action) => void;
function isAction(a: unknown): a is Action { return true; }
function isKeyboardAction(a: unknown): a is KeyboardAction { return true; }
function test(unknownAction: unknown) {
// This will report error for subclass
if (isKeyboardAction(unknownAction)) {
type Action = typeof unknownAction;
const handler: (action: Action) => void = {} as any;
genericHandler = handler; // <-- Error here
}
// Same code as above, but this will *NOT* report error for superclass
if (isAction(unknownAction)) {
type Action = typeof unknownAction;
const handler: (action: Action) => void = {} as any;
genericHandler = handler;
}
}
As you see class narrowing does not always increase the set of actions that are allowed to do. I believe this ?. operator also faces similar situation.
Beside theoretical issue, in practice use, people will just be fine to fix the optional chaining of a variable when they decide to narrow the type. Comparing to using any, this feature will indeed benefit more than the harms.
Regarding the breaking change concern, if this proposal is published along with the type narrowing of unknown of in operator, we should be free from introducing breaking change.
I think the real weirdness is that it'd break the operational directionality of unknown. Normally for any type S that's a subtype of T, if an operation is allowed on T then it's definitely allowed on S, but now unk?.prop is valid when e.g. ({ x: 1 })?.prop isn't even though { x: 1 } is by definition a subtype of unknown.
Isn't this also true for any?
This would lead to some subtle breakage in the future, e.g. let's say you wrote
The proposal is to make this code OK, but then in the future it'd be a breaking change for us to narrow x to { y: unknown } in the body of the if, which seems bad - narrowing should only ever increase the set of things you're allowed to do.
It does increase it from unknown to { y: T } which means we can safely do things like typeof x.y which wouldn't be possible on unknown.
For a concrete example, the famous react-router's Route component's children prop's location state can not be known and so it rightly sets the location param to Location<unknown>.
Now referring to the state is pretty common, here is an example similar to the official documentation:
functionLoginPage(){constlocation=useLocation();const{ from }=location.state||{from: "/"}};
....};
Unpacking from with typescript when state is unknown becomes pretty cumbersome without allowing optional chaning to write:
const{ from }=typeofstate?.from==="string" ? state : {from: "/"}`
Or maybe there is a way to handle this simply without optional chaining on unknown?
Considering that this is possible with any, why shouldn't it be possible with unknown? At least with unknown unlike any, it is clear that nothing is known about the return value of this function and you must narrow the type before using it, unlike if it had returned any.
Ryan Cavanaugh (@RyanCavanaugh) becauae the entire purpose of ?. is to be able to navigate through all JS types - ie, x?.foo is guaranteed to always be unknown, in JS, when x is unknown. It may be that TS's design means that that's not a valid property to extract based on the type of the LHS and the name of the property on the RHS - but I'm not sure why that would result in anything but the same result as x.foo.
In other words, the only difference between x.foo and x?.foo should be when x can be null or undefined - in which case, x?.foo results in undefined. As it is now, TS codebases are forced to use any instead of unknown when using optional chaining, which makes the code less type-safe.
Reacted by Eric S. Rogstad, Omeid Matten, Sebastian Fredriksson Bernholtz, peterhudec-sigtech, htbkoo, Stepan Hilbert, Eero Ruohola and DominoPivot
TypeScript would error on that, same as we would error on x.foo if x were object or { }. Are you saying it should error, or should not error?
It seems like "New syntax constructs should behave like their desugarings" would be an uncontroversial interpretation but that's not what I'm hearing here.
Ryan Cavanaugh (@RyanCavanaugh)value.foo, specifically, would error, you're right, but let's say it was value?.toString - that shouldn't error - it'd either be undefined or a toString function.
Considering that this is possible with any, why shouldn't it be possible with unknown?
Why should two types designed for completely opposite purposes (any being the most-permissive, unknown the least) behave the same?
any isn't actually more permissive, it is TypeScript's coercion rules that allows you to use it as any type you like. Both any and unknown indicate lack of type information.
The reason the parallel is important is because as already mentioned, with unknown you can communicate the unsafe nature of your code and afford a degree of type-safety that isn't possible with any. So it is important to improve the ergonomics of working with unknown. This is consistent with TypeScript design goal of ergonomics over soundness.
Reacted by Jordan Harband, astlouisf, Eric S. Rogstad, Sebastian Fredriksson Bernholtz and Leon Hoos
Based off the mention in #46314, I would guess that the potential bug would in the class of misspellings of properties i.e. a?.toStirng() would almost certainly be an error, but would not cause a run-time error leading to a difficult to find mistake. That's probably the best argument I've seen against it.
Thanks for your reply, I just wanted to focus on the toStirng part: aren't typos in type declarations always a problem? If you force type declarations (e.g. Pimm "de Chinchilla" Hogeling (@Pimm)'s proposal) you end up shifting the typo from point of use to point of declaration.
The comment you linked to (#46314) says short-circuiting would create the following risk:
if(a?.foo){a?.boo.yadda();// oops}
Maybe someone has a more realistic example, because this is precisely the kind of code you use optional chaining to avoid. You'd write:
a?.foo.yadda();
that's the point of null coalescing member access, as I understand it. But how would you do this currently? Cast to any? Same problem. Type casting to a custom type with explicit checking? Same problem, right?
I guess my question is: Is there a solution to handling unknown in TS, currently, which is safer than optional chaining? I don't see optional chaining as a concession on any front, I'd love to understand what we'd be giving up.
Thanks for your reply, I just wanted to focus on the toStirng part: aren't typos in type declarations always a problem? If you force type declarations (e.g. Pimm "de Chinchilla" Hogeling (@Pimm)'s proposal) you end up shifting the typo from point of use to point of declaration.
I was just saying that's the best argument against, not that I was a good argument against lol.
I'm personally advocating for optional chaining to be allowed on unknown for mathematical reasons. Set theory, the basis of the type system itself, and the nature of the ?. operator seem to indicate optional chaining should be allowed. It both provides justification for its use, and a concrete ground to argue against it being expanded to other operators, thus avoiding the slippery slope that gets bandied about.
The case of typos is a valid concern, but it becomes a question of what's more important: a logically consistent type system or avoiding a class of run-time errors. The type system is supposed to help avoid the latter, but does that make it less important? I don't think so, but others clearly disagree.
But even the argument about avoidance of runtime errors has to be taken as what actually is going to prevent more run time errors, not what might. That ignores the human element. If more of the community stops casting to any because of optional chaining on unknown, that's safer code.
Reacted by Jordan Harband, Hraban, Omeid Matten, Václav R. Gröhling, Yuichiro Tachibana (Tsuchiya), Alexandre Fernandez, Klink, Daniel Mittereder, Sebastian Fredriksson Bernholtz, peterhudec-sigtech and 5 more
For those interested, you can somewhat emulate this behaviour like this:
typeSafeAny={[key: PropertyKey]: SafeAny,}|undefined|null;constx=nullasSafeAny;console.log(x?.children?.[0]?.age);// This is allowedconsole.log(x?.children[0]?.age);// This is an error
The caveats here are:
You need to explicitly cast most types to SafeAny (... as unknown as SafeAny)
This doesn't allow function calls, with or without ?.().
Type narrowing is difficult, because typeof doesn't work correctly on this type (technically it is correct, but because we're lying to the compiler it makes the wrong assumptions). You can work around this by using type guards instead.
Reacted by Sebastian Fredriksson Bernholtz, snarbies and Dan Falk
decodedData?.a?.b?.c;// Type is number | undefined
decodedData?.a?.b?.c should be unknown in JSON.parse() ,or it is not safe
constc=decodedData?.a?.b?.c// Type is number | undefinedif(c){c// number , but is it really a number type in js runtime ? }typeUnreliable<T>=Textendsobject
? {[keyinkeyofT]-?: Unreliable<T[key]>}
: unknown
functionisTom(cat: unknown){constfirstName=cat?.name?.firstif(typeoffirstName==='string'&&firstName==='Tom')return'Yes'elsereturn'No'}isTom('Jerry')// NoisTom(null)// NoisTom(123)// No
Code above will cause a compiling error in TS.
To solve this problem, I have to change unknown to any, or use type assertion. But I believe we should not encourage to use any and type assertion in TS.
Disallowing optional chaining on unknown reduces its utility and forces unnecessary boilerplate. There are many common scenarios where this limitation becomes frustrating. For example:
try{// some code}catch(err: unknown){console.log(err?.message);// Not allowed}
constresponse: unknown=awaitgetResponse();constisOk=response?.status==='ok';// Not allowedif(isOk) ...
constdata: unknown=awaitgetData();constnestedValue=data?.some?.nested?.value;// Not allowedif(isWhatINeed(nestedValue)) ...
Is it possible to reconsider this issue?
Reacted by Chris Ackerman, oli, Chow Loong Jin, fire332, JuanGalilea, Omeid Matten, Johan Grundberg, glebbash and Thomas
constsomeObject={foo: 'bar'};constkeys=Object.keys(someObject);// string[]for(constkeyofkeys){// error: No index signature with a parameter of type `string` was found on type `{ foo: string }`console.log(someObject?.[key]);}
being able to optional chain anything into any object would just reduce the painpoints caused by Object.keys not returning keyof type which Ryan Cavanaugh (@RyanCavanaugh) seems to have asked and answered in stackoverflow just to make it easier for devs struggling against this to find out why it is the way it is.
Given that
Object.keys returns keyof T
is the one that was decided to not be true (which is good), at least a change like this would make the struggle of dealing with it less painful.
FWIW, here is a little helper function that just takes any value and performs a sequence of optional chaining property accesses on it (accepts any input and always produces unknown result):
FWIW, here is a little helper function that just takes any value and performs a sequence of optional chaining property accesses on it (accepts any input and always produces unknown result):
FWIW, here is a little helper function that just takes any value and performs a sequence of optional chaining property accesses on it (accepts any input and always produces unknown result):
// 1. Recursive Type to traverse T based on keys in PtypeGetPath<T,Pextendsreadonlystring[]>=Pextends[infer Key, ...infer Rest]
? Restextendsreadonlystring[] ? KeyextendskeyofNonNullable<T>// Found valid key: Recurse deeper// We add | undefined if the parent was nullable (simulating ?.)
?
|GetPath<NonNullable<T>[Key],Rest>|(undefinedextendsT ? undefined : never)|(nullextendsT ? undefined : never)// Invalid key or T is unknown: Return unknown per requirements
: unknown
: never
: T// End of path: return the resulting type// 2. The ImplementationconstoptionalChain=<T,constPextendsstring[]>(obj: T,path: P,): GetPath<T,P>=>{// We cast the result because TS cannot verify the complex recursive reduction at runtimereturnpath.reduce((acc,prop)=>(accasany)?.[prop],obj)asGetPath<T,P>}typeUser={createdAt?: Dateprofile: {name: stringage: unknown// Explicit unknownaddress?: {street: string}}}constuser: User={profile: {name: 'Alice',age: 25,address: {street: 'Liberation Street'}},createdAt: newDate(),}// 1. Happy Pathexportconstname: string=optionalChain(user,['profile','name'])exportconstcreatedAt: Date|undefined=optionalChain(user,['createdAt'])exportconststreet: string|undefined=optionalChain(user,['profile','address','street',])// 2. Path stops early (simulates optional chaining)exportconstprofile: {name: string;age: unknown}=optionalChain(user,['profile',])// 3. Path hits 'unknown' property// Result: unknown (Because user.profile.age is unknown)exportconstage=optionalChain(user,['profile','age'])// 4. Path continues THROUGH 'unknown'// Result: unknown (Because we can't infer keys of unknown)exportconstinvalidDeep=optionalChain(user,['profile','age','oops'])// 5. Path does not exist// Result: unknownexportconstbadKey=optionalChain(user,['profile','wrongKey'])
the only problem is that you don't get autocomplete for path elements
https://github.com/sindresorhus/dot-prop can be used to "get, set, or delete a property from a nested object using a dot path [or an array path]" that will return undefined for nonexistent paths.
Daniel Rosenwasser (@DanielRosenwasser) while I understand the architectural dead-ends and narrowing conflicts that led to this issue being closed, the underlying pain point remains a daily friction for many developers.
I agree that making unknown?.field resolve to unknown globally could introduce subtle bugs, but the current strictness forces developers into unsafe type-casting (as any) for incredibly standard JavaScript patterns.
Context
Three quite common scenarios where this issue is a real pain is:
NOTE: showing only the JavaScript versions. If you could show a good TypeScript solutions for these, then the issue should rightfully stay closed.
Error handling
Quite a lot of libraries set some kind of code on an error that you could use to check error type.
try{// ....}catch(error){if(error?.code!==Lib.RETRIABLE_ERROR_CODE){throwerror;}// good to retry the call after a timeout}
JSON.parse results handling in untyped apis
constdataFromApi=JSON.parse(rawDataFromApi)constuserName=dataFromApi?.user?.nameif(typeofuserName==="string"){// value is good to use}
A type that behaves like exactly like unknown, but permits optional chaining/property access to yield further dynamic types. This avoids the total type-check shutdown of any.
A localized compiler flag or block-level directive: "allowOptionalChainingOnUnknown": true or /* @ts-allow-in-next-block: unknown-optional-chaining */
While tsconfig flags aren't the best looking solution here (although this might be the simplest option to implement), allowing a block-scoped directive (similar to ESLint rules) to permit optional chaining on unknown could localize the risk to just those error-handling or json handling blocks.
There definitely is a middle ground where we don't have to choose between writing verbose (and sometimes runtime affecting) type-guards or completely surrendering to any just to safely read a nested property.
I hope this issue can be re-evaluated, I think enough people has raised a voice around this to signal that its often a real pain, especially in codebases that weren't written with TypeScript in mind and are gradually trying to get more type safety without testing every single change after typing existing code, because getting rid of anys quite often requires runtime logic changes that are only needed to satisfy the TS compiler.
Reacted by fire332, Chris Ackerman, Thomas and Steven Vroom
Activity
[-]Optional chaining of unknown should be allowed[/-][+]Optional chaining of unknown should be unknown[/+]ilogico commentedon Mar 31, 2020
This is as safe as allowing property access on
{}(unknownis pretty much the same as{} | null | undefined) or allowing access to unknown properties in interfaces in general.I don't think you should be able to do something with a type and not with its sub-types (we already have
anyfor these things).And if this would be allowed, why should it be restricted to the optional chaining syntax?
I believe it is semantically equivalent.
RyanCavanaugh commentedon Mar 31, 2020
I think the real weirdness is that it'd break the operational directionality of
unknown. Normally for any typeSthat's a subtype ofT, if an operation is allowed onTthen it's definitely allowed onS, but nowunk?.propis valid when e.g.({ x: 1 })?.propisn't even though{ x: 1 }is by definition a subtype ofunknown.This would lead to some subtle breakage in the future, e.g. let's say you wrote
The proposal is to make this code OK, but then in the future it'd be a breaking change for us to narrow
xto{ y: unknown }in the body of theif, which seems bad - narrowing should only ever increase the set of things you're allowed to do.falsandtru commentedon Mar 31, 2020
Should use
x?.['y']instead.hktonylee commentedon Apr 1, 2020
Hi Ryan thank you for your excellent example. I agree that narrowing should only ever increase the set of things that are allowed to do. But I can think of a counterexample involving the use of contravariance.
As you see class narrowing does not always increase the set of actions that are allowed to do. I believe this
?.operator also faces similar situation.Beside theoretical issue, in practice use, people will just be fine to fix the optional chaining of a variable when they decide to narrow the type. Comparing to using
any, this feature will indeed benefit more than the harms.Regarding the breaking change concern, if this proposal is published along with the type narrowing of
unknownofinoperator, we should be free from introducing breaking change.omeid commentedon Dec 17, 2020
Isn't this also true for
any?I think you meant
console.log(x?.y)?It does increase it from
unknownto{ y: T }which means we can safely do things liketypeof x.ywhich wouldn't be possible onunknown.omeid commentedon Dec 17, 2020
For a concrete example, the famous react-router's
Routecomponent's children prop's location state can not be known and so it rightly sets thelocationparam toLocation<unknown>.Now referring to the state is pretty common, here is an example similar to the official documentation:
Unpacking
fromwith typescript whenstateis unknown becomes pretty cumbersome without allowing optional chaning to write:Or maybe there is a way to handle this simply without optional chaining on unknown?
omeid commentedon Dec 18, 2020
Gonçalo Fernandes (@ilogico)
Considering that this is possible with
any, why shouldn't it be possible withunknown? At least withunknownunlikeany, it is clear that nothing is known about the return value of this function and you must narrow the type before using it, unlike if it had returnedany.RyanCavanaugh commentedon Dec 18, 2020
Why should two types designed for completely opposite purposes (
anybeing the most-permissive,unknownthe least) behave the same?ljharb commentedon Dec 18, 2020
Ryan Cavanaugh (@RyanCavanaugh) becauae the entire purpose of
?.is to be able to navigate through all JS types - ie,x?.foois guaranteed to always beunknown, in JS, whenxisunknown. It may be that TS's design means that that's not a valid property to extract based on the type of the LHS and the name of the property on the RHS - but I'm not sure why that would result in anything but the same result asx.foo.In other words, the only difference between
x.fooandx?.fooshould be whenxcan be null or undefined - in which case,x?.fooresults inundefined. As it is now, TS codebases are forced to useanyinstead ofunknownwhen using optional chaining, which makes the code less type-safe.RyanCavanaugh commentedon Dec 18, 2020
Jordan Harband (@ljharb) I can't tell what you're trying to say with that.
If you desugared
into
TypeScript would error on that, same as we would error on
x.fooifxwereobjector{ }. Are you saying it should error, or should not error?It seems like "New syntax constructs should behave like their desugarings" would be an uncontroversial interpretation but that's not what I'm hearing here.
ljharb commentedon Dec 18, 2020
Ryan Cavanaugh (@RyanCavanaugh)
value.foo, specifically, would error, you're right, but let's say it wasvalue?.toString- that shouldn't error - it'd either beundefinedor a toString function.omeid commentedon Dec 19, 2020
anyisn't actually more permissive, it is TypeScript's coercion rules that allows you to use it as any type you like. Bothanyandunknownindicate lack of type information.The reason the parallel is important is because as already mentioned, with
unknownyou can communicate the unsafe nature of your code and afford a degree of type-safety that isn't possible withany. So it is important to improve the ergonomics of working withunknown. This is consistent with TypeScript design goal of ergonomics over soundness.24 remaining items
hraban commentedon Dec 24, 2021
Thanks for your reply, I just wanted to focus on the
toStirngpart: aren't typos in type declarations always a problem? If you force type declarations (e.g. Pimm "de Chinchilla" Hogeling (@Pimm)'s proposal) you end up shifting the typo from point of use to point of declaration.The comment you linked to (#46314) says short-circuiting would create the following risk:
Maybe someone has a more realistic example, because this is precisely the kind of code you use optional chaining to avoid. You'd write:
that's the point of null coalescing member access, as I understand it. But how would you do this currently? Cast to
any? Same problem. Type casting to a custom type with explicit checking? Same problem, right?I guess my question is: Is there a solution to handling
unknownin TS, currently, which is safer than optional chaining? I don't see optional chaining as a concession on any front, I'd love to understand what we'd be giving up.kralphs commentedon Dec 24, 2021
I was just saying that's the best argument against, not that I was a good argument against lol.
I'm personally advocating for optional chaining to be allowed on unknown for mathematical reasons. Set theory, the basis of the type system itself, and the nature of the
?.operator seem to indicate optional chaining should be allowed. It both provides justification for its use, and a concrete ground to argue against it being expanded to other operators, thus avoiding the slippery slope that gets bandied about.The case of typos is a valid concern, but it becomes a question of what's more important: a logically consistent type system or avoiding a class of run-time errors. The type system is supposed to help avoid the latter, but does that make it less important? I don't think so, but others clearly disagree.
But even the argument about avoidance of runtime errors has to be taken as what actually is going to prevent more run time errors, not what might. That ignores the human element. If more of the community stops casting to any because of optional chaining on unknown, that's safer code.
Jcparkyn commentedon Feb 8, 2022
For those interested, you can somewhat emulate this behaviour like this:
The caveats here are:
SafeAny(... as unknown as SafeAny)?.().typeofdoesn't work correctly on this type (technically it is correct, but because we're lying to the compiler it makes the wrong assumptions). You can work around this by using type guards instead.Alexandre-Fernandez commentedon Apr 29, 2022
this is how I manage this problem (feel free to use it or improve it, for now it only works for one level deep properties) :
yukinotech commentedon Jul 28, 2022
decodedData?.a?.b?.cshould beunknowninJSON.parse(),or it is not safeadrian-gierakowski commentedon Sep 30, 2022
Thanks for this Alexandre Fernandez (@Alexandre-Fernandez)!
I'm using it with a little tweak: instead of
I use:
which makes the following safer:
When using
object,subProp's type is implicitly assigned ananytype (which is obviously unsafe) and causes an error whennoImplicitAnyis enabled.zanminkian commentedon Aug 13, 2023
Code above will cause a compiling error in TS.
To solve this problem, I have to change
unknowntoany, or use type assertion. But I believe we should not encourage to useanyand type assertion in TS.NicholasAntidormi commentedon Jan 28, 2025
Disallowing optional chaining on
unknownreduces its utility and forces unnecessary boilerplate. There are many common scenarios where this limitation becomes frustrating. For example:Is it possible to reconsider this issue?
JuanGalilea commentedon Nov 7, 2025
Also it would solve issues like
being able to optional chain anything into any object would just reduce the painpoints caused by Object.keys not returning keyof type which Ryan Cavanaugh (@RyanCavanaugh) seems to have asked and answered in stackoverflow just to make it easier for devs struggling against this to find out why it is the way it is.
Given that
is the one that was decided to not be true (which is good), at least a change like this would make the struggle of dealing with it less painful.
grundb commentedon Feb 11, 2026
FWIW, here is a little helper function that just takes any value and performs a sequence of optional chaining property accesses on it (accepts any input and always produces
unknownresult):adrian-gierakowski commentedon Feb 11, 2026
That's a sledgehammer: you only want result to be unknown if you are chaining on an unknown.
grundb commentedon Feb 11, 2026
For sure. But it gets the job done for the common case of "I have an
unknownthing and I want anotherunknownthing"adrian-gierakowski commentedon Feb 11, 2026
LLMs can do better:
the only problem is that you don't get autocomplete for path elements
mfulton26 commentedon Feb 11, 2026
https://github.com/sindresorhus/dot-prop can be used to "get, set, or delete a property from a nested object using a dot path [or an array path]" that will return
undefinedfor nonexistent paths.glebbash commentedon Jun 3, 2026
Daniel Rosenwasser (@DanielRosenwasser) while I understand the architectural dead-ends and narrowing conflicts that led to this issue being closed, the underlying pain point remains a daily friction for many developers.
I agree that making
unknown?.fieldresolve tounknownglobally could introduce subtle bugs, but the current strictness forces developers into unsafe type-casting (as any) for incredibly standard JavaScript patterns.Context
Three quite common scenarios where this issue is a real pain is:
Error handling
Quite a lot of libraries set some kind of code on an error that you could use to check error type.
JSON.parseresults handling in untyped apisLibraries that accept
unknowntypePossible solutions
A restricted
dynamicorloose_unknowntypeA type that behaves like exactly like
unknown, but permits optional chaining/property access to yield furtherdynamictypes. This avoids the total type-check shutdown ofany.A localized compiler flag or block-level directive:
"allowOptionalChainingOnUnknown": trueor/* @ts-allow-in-next-block: unknown-optional-chaining */While
tsconfigflags aren't the best looking solution here (although this might be the simplest option to implement), allowing a block-scoped directive (similar to ESLint rules) to permit optional chaining onunknowncould localize the risk to just those error-handling or json handling blocks.There definitely is a middle ground where we don't have to choose between writing verbose (and sometimes runtime affecting) type-guards or completely surrendering to
anyjust to safely read a nested property.I hope this issue can be re-evaluated, I think enough people has raised a voice around this to signal that its often a real pain, especially in codebases that weren't written with TypeScript in mind and are gradually trying to get more type safety without testing every single change after typing existing code, because getting rid of
anys quite often requires runtime logic changes that are only needed to satisfy the TS compiler.