-
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
Why are Object.create(null)
and {}
treated differently regarding undefined-exclusion?
#52698
Comments
Because |
Indeed, but why is it not treated as |
When trying to avoid prototype pollution and similar issues, dealing with null-prototype objects reduces risks significantly. Any time I ever have |
Because |
Maybe it should default to The current behavior seems suboptimal, and having to cast it when its type should already be implied via what it's being assigned to is undesirable. E.g. to change from POJO to null prototype object without affecting surrounding code we have to do quite a lot of typing: // With POJO:
a.b = {};
// With null prototype (so verbose!):
a.b = Object.create(null) as object; // or Record<any, any> Related issue from 2015: #3865 |
I guess you could create an issue for that: Lib change issue template In the meantime you can simply use declaration merging to create an overload for your own code base. Just create a interface ObjectConstructor {
create(n: null): {}
} |
Keep in mind that typescript will still treat the object (in the type system) as if it derives from |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
🔎 Search Terms
Object.create(null)
🕗 Version & Regression Information
Object.create(null)
but there doesn't seem to be any.⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
In the first block, everything is fine. In the second block, the
a.b.c = 1
line issues the TypeScript error'a.b' is possibly 'undefined'
.🙂 Expected behavior
Just as line 5 implies
a.b
exists, line 13 should do the same.The text was updated successfully, but these errors were encountered: