簡體   English   中英

你如何導出道具名稱和類型而不是到處定義它?

[英]How do you export a prop name and the type instead of defining it everywhere?

說我有這樣的事情:

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

然后我可以在像這樣的組件中使用

type Props = {
   style: Style
}

但不必在每個組件中定義它,我寧願這樣做

type Props = {
  someRandomProp
} & Style

這樣我就不需要在任何地方都將道具添加為類型

我該怎么做呢?

你幾乎可以像你展示的那樣做到這一點:

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

然后

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

游樂場鏈接

參考官方文檔: Typescript Docs

type Animal = {
  name: string
}

type Bear = Animal & { 
  honey: boolean 
}

您還可以為每個組件使用接口而不是類型,並使它們從原始預定義類型擴展,如下所示:

type Animal = {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

請注意,擴展在類型之間或從接口到類型之間不起作用。 只有接口和類可以從另一個實體擴展。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM