我有以下界面:
export interface WithQueryBuilder {
queryBuilderProps: {
columns: { [key: string]: { enabled: boolean; label: string; key: string } };
meta: Record<string, unknown>;
filters: Record<string, unknown>;
search: {
[key: string]: { enabled?: boolean; key: string; label: string; value: null | string };
};
page: number;
sort: null;
};
}
我現在想創建一個新界面,其中包含屬性queryBuilderProps和一些其他屬性。我嘗試了以下方法:
interface TableProps extends Pick<WithQueryBuilder, 'queryBuilderProps'> {
onUpdate?: () => void;
}
我期望的是這樣的型別:
{
onUpdate: ...,
columns: ...,
filters: ...,
search: ...,
[...]
}
相反,型別如下所示:
{
onUpdate: ...,
withQueryBuilder: { columns, meta, filters, ...),
}
我理解為什么會發生這種情況,但我想知道是否有辦法“挑選”所有子定義而不是queryBuilderProps整體。有點像 TypeScript 的擴展運算子。
有這樣的東西存在嗎?
uj5u.com熱心網友回復:
我們可以使用 anindexed access type來查找另一種型別的特定屬性:
型別人 = { 年齡:數字;名稱:字串;活著:布林值}; 型別年齡=人[“年齡”];型別年齡 = 數字
TypeScript 手冊:索引訪問型別
您仍然可以使用interface如下TableProps:
export interface WithQueryBuilder {
queryBuilderProps: {
columns: { [key: string]: { enabled: boolean; label: string; key: string } };
meta: Record<string, unknown>;
filters: Record<string, unknown>;
search: {
[key: string]: { enabled?: boolean; key: string; label: string; value: null | string };
};
page: number;
sort: null;
};
}
// Here is the important part, this is the correct way to get the sub-type
type QueryBuilderProps = WithQueryBuilder['queryBuilderProps']
// You can still use interface here
interface TableProps extends QueryBuilderProps {
onUpdate?: () => void;
}
const obj: TableProps = {
onUpdate() {},
columns: {
"key": { enabled: true, label: `label`, key: `key` },
},
meta: {},
filters: {},
search: {},
page: 1,
sort: null,
}
// The following will throw error:
// An interface can only extend an identifier/qualified-name with optional type arguments.(2499)
interface TableProps2 extends WithQueryBuilder['queryBuilderProps'] {
onUpdate?: () => void;
}
TS游樂場
uj5u.com熱心網友回復:
Interface您可以使用方括號訪問 an 的子屬性[]:
type TableProps = WithQueryBuilder["queryBuilderProps"] & {
onUpdate?: () => void
}
沙盒
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/468565.html
標籤:javascript 打字稿
上一篇:FireBase值未正確列印
下一篇:linux基本使用
