Home > database >  How do you export a prop name and the type instead of defining it everywhere?
How do you export a prop name and the type instead of defining it everywhere?

Time:04-29

Say I have something like this:

export type Style = Pick<
  React.CSSProperties,
  "margin" | "marginBottom"
>

and I can then use in a component like

type Props = {
   style: Style
}

but instead of having to define that in EVERY component I'd rather do

type Props = {
  someRandomProp
} & Style

and that way I don't need to add the prop as a type everywhere

how do I do this?

CodePudding user response:

You can do it very nearly as you've shown:

export type Style = Pick<
    React.CSSProperties,
    "margin" | "marginBottom"
>;
export type StyleProp = {
    style: Style
};

then

import { StyleProp } from "./somewhere";
// ...
type Props = {
    someRandomProp: string; // or whatever
} & StyleProp;

Playground link

CodePudding user response:

Refer to the oficial documentation: Typescript Docs

type Animal = {
  name: string
}

type Bear = Animal & { 
  honey: boolean 
}

You can also use interfaces instead of types for each component and make them extend from the original predefined type like this:

type Animal = {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

Notice that extending doesn't work between types or from an interface to a type. Only interfaces and classes may extend from another entity.

  • Related