考慮一個型別PageProps : Record<string, Type>:
type PageProps = Record<
string,
| {
type: "title";
title: Array<{
type: "text";
text: {
content: string;
link: {
url: string;
} | null;
};
plain_text: string;
href: string | null;
}>;
}
| {
type: "rich_text";
rich_text: Array<
| {
type: "text";
text: {
content: string;
link: {
url: string;
} | null;
};
plain_text: string;
href: string | null;
}
| {
type: "equation";
equation: {
expression: string;
};
plain_text: string;
href: string | null;
}
>;
id: string;
}
| {
type: "number";
number: number;
id: string;
}
| {
type: "url";
url: string;
id: string;
}
>;
如何從上面提取以下型別PageProps : Record<Keys, Type>:
type RichText = {
type: "rich_text";
rich_text: Array<
| {
type: "text";
text: {
content: string;
link: {
url: string;
} | null;
};
plain_text: string;
href: string | null;
}
| {
type: "equation";
equation: {
expression: string;
};
plain_text: string;
href: string | null;
}
>;
id: string;
}
我試過Pick and Extract但無法讓它為Record<Keys, Type>.
在TS Playgroud 中試試這個
注意:
PageProps來自模塊,因此無法對其進行編輯/重構。
uj5u.com熱心網友回復:
您可以像這樣訪問受歧視聯合的這一部分:
type RichText = Extract<PageProps[string], {type: "rich_text"}>;
這本質上依賴于PageProps[string]一個可區分的聯合這一事實,并利用了 TypeScript 分布在用作泛型型別引數的聯合型別上的事實。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326554.html
標籤:打字稿
上一篇:反應形式等于密碼驗證
