說我有這樣的事情:
export type Style = Pick<
React.CSSProperties,
"margin" | "marginBottom"
>
然后我可以在像這樣的組件中使用
type Props = {
style: Style
}
但不必在每個組件中定義它,我寧愿做
type Props = {
someRandomProp
} & Style
這樣我就不需要在任何地方添加道具作為型別
我該怎么做呢?
uj5u.com熱心網友回復:
你幾乎可以做到這一點,就像你展示的那樣:
export type Style = Pick<
React.CSSProperties,
"margin" | "marginBottom"
>;
export type StyleProp = {
style: Style
};
然后
import { StyleProp } from "./somewhere";
// ...
type Props = {
someRandomProp: string; // or whatever
} & StyleProp;
游樂場鏈接
uj5u.com熱心網友回復:
參考官方檔案:Typescript Docs
type Animal = {
name: string
}
type Bear = Animal & {
honey: boolean
}
您還可以為每個組件使用介面而不是型別,并使它們從原始預定義型別擴展,如下所示:
type Animal = {
name: string
}
interface Bear extends Animal {
honey: boolean
}
請注意,擴展在型別之間或從介面到型別之間不起作用。只有介面和類可以從另一個物體擴展。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466994.html
標籤:javascript 反应 打字稿
上一篇:如何在通用函式中正確使用型別?
