Repository navigation
hasOwnProperty return type #41915
Copy link
Copy link
Open
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
Search Terms
hasOwnProperty
Suggestion
interface Object {
hasOwnProperty<Key extends PropertyKey>(v: Key): this is this & Record<Key, unknown>;
}Use Cases
To be able to use the property of an object after it has been tested for its existence.
Current behavior:
// Property 'testProp' does not exist on type 'object'.(2339)
obj.hasOwnProperty('testProp') && typeof arg.testProp === 'string' Examples
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 feature would agree with the rest of TypeScript's Design Goals.
Reacted by Luke Page, Justin Constantino, ExE Boss, Sebastian Malton, Titian Cernicova-Dragomir, Emily, Seyi Adebajo, CallMeLaNN, Daniel Pallares, Kyra and 4 more
Metadata
Metadata
Assignees
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Activity
WORMSS commentedon Dec 10, 2020
PS: if this can be 'fixed' for
'testProp' in objthat would be amazing too.MartinJohns commentedon Dec 10, 2020
Duplicate of #18282.
MartinJohns commentedon Dec 10, 2020
This is tracked by #21732.
WORMSS commentedon Dec 10, 2020
You say it's a duplicate, but it seems their example was a far inferior attempt?
None of the examples in #18282 would be as seamless as
this is this & Record<Key, unknown>Maybe due to 3 years ago when TS was not as mature.
Nokel81 commentedon Jan 12, 2021
This would be amazing! Working with
unknownis really annoying currently because even after doing an explicit check (what will happen at runtime) it still treats it as non existing.Take the following example:
Currently the only solution is to define this function itself and use it or cast
objtoRecord<string, unknown>and go from there.This solution doesn't work for non-literals (as in it passes compilation but doesn't further narrow the type)./
Malix-Labs commentedon Nov 30, 2023
Ryan Cavanaugh (@RyanCavanaugh) #41915 (comment)
What feedback still needs to be awaited?