typescriptreact-nativelinear-gradientsnative-base

How do I combine TypeScript Object/Record typing, code completion and VSCode "Go to Definition" feature?


I am combining react native, native base and linear gradients which looks something like this:

<Box
  bg={{
    linearGradient: {
      colors: ['lightBlue.300', 'violet.800'],
      start: [0, 0],
      end: [1, 0],
    },
  }}
/>

Native base exports this type as ILinearGradientProps. My application includes 15+ linear gradients which need to be accessed in different components. I added a LinearGradients object which looks something like this but with actual props filled in (colors, start, end):

import { ILinearGradientProps } from 'native-base';

type LGKey = 'primary' | 'secondary' | 'success' | ...;

export const LinearGradients: Record<LGKey, ILinearGradientProps> = {
  primary: { ...linearGradientProps },
  secondary: { ...linearGradientProps },
  success: { ...linearGradientProps },
  ...

With the above typing Record<LGKey, ILinearGradientProps>:

However, using Ctrl/Cmd + Click or the "Go to Definition" feature from VSCode (and maybe other code editors too) directly on the property LinearGradients.primary does not work. It would be good if VSCode could direct me to the specific property within LinearGradients.

If I change the code to like below, the go to definition feature works but it doesn't seem like good TS code IMO:

export const LinearGradients = {
  primary: { ...linearGradientProps } as ILinearGradientProps,
  secondary: { ...linearGradientProps } as ILinearGradientProps,
  success: { ...linearGradientProps } as ILinearGradientProps,
  ...

Does anyone know how I can have all four of these features working together (without asserting the type for every new property with as like above) to achieve:

or is this just a limitation of TypeScript right now?

This has come up for me a few times now and I cannot find much about this online, so would really appreciate any help. Thanks


Solution

  • // ts@>=4.9
    export const LinearGradients = {
      primary: { ...linearGradientProps },
      secondary: { ...linearGradientProps },
      success: { ...linearGradientProps },
    } satisfies Record<LGKey, ILinearGradientProps>
    

    https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator