Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@sergiocarneiro
Copy link
Contributor

The type of the value returned by useSafeAreaInsetsStyle is always:

{
  paddingTop?: string | number;
  paddingBottom?: string | number;
  paddingStart?: string | number;
  paddingEnd?: string | number;
  marginTop?: string | number;
  marginBottom?: string | number;
  marginStart?: string | number;
  marginEnd?: string | number;
}

Not only is inaccurate, but also wrong. string is never returned by useSafeAreaInsets, nor undefined.

This broad type makes it harder to perform operations with the safe-area values, and it's uncertain whether developers can force-cast to number without looking into the source code of react-native-safe-area-context.

By adding a little complexity to the hook, full type inference can be added.

Result

const $insets = useSafeAreaInsetsStyle(["bottom"]);
// { paddingBottom: number }

const $insets = useSafeAreaInsetsStyle(["top"], "margin");
// { marginTop: number }

const $insets = useSafeAreaInsetsStyle(["left", "right"], "padding");
// { paddingLeft: number; paddingRight: number }

Caveats

The type displayed while hovering the property is not simplified, e.g.:

SafeAreaInsetsStyle<"padding", ("right" | "left")[]>
Workaround

We could introduce an extra type utility Pretty:

type Pretty<T> = {
  [K in keyof T]: T[K]
}

export type SafeAreaInsetsStyle<
  Property extends "padding" | "margin" = "padding",
  Edges extends Array<ExtendedEdge> = Array<ExtendedEdge>
> = Pretty<{
  [K in Edges[number] as `${Property}${Capitalize<K>}`]: number;
}>;

Result

Pretty<{
  paddingBottom: number;
}>

@sergiocarneiro sergiocarneiro force-pushed the feat/type-safe-area-insets-style branch from 800efc9 to 254c0ff Compare June 5, 2023 01:48
@markrickert
Copy link
Member

Hey @sergiocarneiro I just tried this out and i was getting a typescript warning with your changes on the latest version of ignite.

I had to change safeAreaEdges: Edges = [] as Edges, to safeAreaEdges: Edges = [] as unknown as Edges, to get typescript 5.3.2 to pass.

Could you rebase on master and have another look at this change?

@markrickert markrickert merged commit a6f9497 into infinitered:master Feb 6, 2024
infinitered-circleci pushed a commit that referenced this pull request Feb 6, 2024
## [9.4.4](v9.4.3...v9.4.4) (2024-02-06)

### Bug Fixes

* **types:** full type inference to `useSafeAreaInsetsStyle` ([#2457](#2457)) ([a6f9497](a6f9497))
@infinitered-circleci
Copy link
Collaborator

🎉 This PR is included in version 9.4.4 🎉

The release is available on:

Your semantic-release bot 📦🚀

@sergiocarneiro sergiocarneiro deleted the feat/type-safe-area-insets-style branch February 6, 2024 19:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants