Fix StyleSheet.flatten returning undefined for falsy values #46294
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.
Closes #46293.
Summary:
StyleSheet.flatten
currently returnsundefined
when called with a falsy value (null/undefined/false/empty string). I ran into this with a conditional style that happened to passfalse
as the style to a component fromreact-native-gesture-handler
. The library usesflatten
to flatten the style prop and then copy some of the computed styles to another component, and assumed that flatten would always return a style object.flatten
returnedundefined
, and I got a runtime error for trying to read properties of undefined.The current behavior is not represented in the TypeScript types for the function. The docs say that
flatten
"flattens an array of style objects, into one aggregated style object", and also don't mention how it might return undefined. I think changingflatten
to return an empty object for falsy values better matches the purpose and current usage of the function, and is a better option than widening the return type to include undefined or leaving this behavior undocumented.Changelog:
[General] [Fixed] - Fix StyleSheet.flatten returning undefined for falsy values
Test Plan:
Tests pass with some changes:
flattenStyle(null)
to be undefined ("should not allocate an object when there is no style"). Since this behavior isn't documented in the types or docs, I don't think it should still be considered the correct behavior. I also think the performance loss is probably very small and worth the correctness.flattenStyle(1234, null)
to be undefined. This test originally expected it to return{}
, but this was changed toundefined
whenReactNativePropRegistry
was removed in a8e3c7f. I think this test was left over from whenStyleSheet.create
returned opaque values, and can be removed.undefined
to{}
).