feat: add findFirstType method to Component #6084
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
Currently, the
findType
method in theComponent
class returns an array of components (Component[]
). This can lead to potential type-safety issues when developers need to access the first element of the result. For example:We've explored several approaches to address this issue:
Using optional chaining:
While this prevents runtime errors, it doesn't fully leverage TypeScript's type system to catch potential issues at compile-time.
Using type assertions:
This approach suppresses TypeScript warnings but doesn't actually solve the underlying issue and can lead to runtime errors.
Using
Array.prototype.at()
:This approach is better but still requires explicitly include the .at(0) call, which can be error-prone.
We've also attempted to modify type definitions to make
findType
return(Component | undefined)[]
, but this led to confusing type information and didn't solve the core issue, or wrap it with lodash'sfirst
method butThese workarounds, while functional, don't provide an ideal solution that combines type safety, clarity, and ease of use. We believe a more robust solution is needed to address this issue consistently across our codebase.
Proposed solution
To address this, we propose adding a new method
findFirstType
to theComponent
class. This method will return either aComponent
instance orundefined
, making it clearer when a component of the specified type is not found.The existing
closestType
method already follows this pattern, so addingfindFirstType
will not only improve consistency but also provide a more type-safe and intuitive way to access the first component of a given type.