-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
"object" can be made to accept primitives due to handling of "{}" #56205
Comments
This isn't unique to |
|
Allowing |
This issue has been marked as "Unactionable" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
π Search Terms
object unknown null
inconsistent behavior around unknown and object
object accepts primitive types through unknown
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?ts=5.3.0-dev.20231024#code/MYewdgzgLgBAZiEMC8MAUAPGAuGIBGAVgKbBQCUKAfDBgNwCwAUKJLPgIYBOK6WuAOXACArgBsxHfGOIAeEWADWYEAHcwVSshoIQmcoxbhoMTgC9emXAFEMwMSIAmchcrVgANDDDixMAD4wCs5wAJZgxI6a1PCI+obMnFxoAMwGzLqp6UzMrCa6AEyWGLgEJGQB3r6VwcRhEY5aNPS5xuzcRahWMEJgohJSMvJKKuo0gT4SNWAh4ZFNsSAF8a1sptwpxbiuo2ALhSs5TEnLAORSwKfZB+f4l9lAA
π» Code
π Actual behavior
Only some of the cases in the code sample error, but
bar
andbar2
don't, despite passing a primitive tofoo
which expects anobject
.This is because
object
acceptsunknown
values once they're checked for null/undefined (i.e. it accepts{}
/NonNullable<unknown>
), and{}
accepts primitives, so primitives can be indirectly accepted asobject
.Relatedly, in the case of
unknown
,NonNullable<T>
ends up behaving differently thanExclude<T, null | undefined>
.π Expected behavior
All the cases in the code sample should error, including
bar
andbar2
when given primitive values.Generally,
object
is the type of all non-primitive values, so passing primitives to it should result in an error. SinceNotNullable<unknown>
(i.e.{}
) includes primitives, passing it asobject
should result in an error.Further,
NotNullable<Type>
is defined as "excluding null and undefined from Type", soExclude<unknown, null | undefined>
should behave the same asNonNullable<unknown>
(and converselyNonNullable<unknown> | null | undefined
should behave the same asunknown
).Additional information about the issue
This inconsistent behavior was introduced in TS 4.8.
Note that while the examples above may seem kind of esoteric, this also appears in the much more common case where
{}
is implicitly inferred thanks to a null check, e.g.:If I had to guess, I suppose it might be due to conflating
{}
's actual meaning (which appears to be "any non-nullish value" - that is, including primitives) vs. what it visually looks like, which is an object.The text was updated successfully, but these errors were encountered: