Options 我創建了一個自定義型別(嵌套物件)。我想使用該型別DefaultProperties來創建一個包含默認屬性的物件。
type Options = {
id: number,
text: string | undefined,
properties: {
title: string,
subtitle: string | undefined,
}
}
type DefaultProperties = Pick<Options, "properties">;
當然默認屬性不能是undefined. 所以我想undefined從我的聯合型別中排除。為此,應該有一個內置函式,例如NonNullable<T>or Exclude<T,UnionType>。
我嘗試了三種不同的洗掉方法,undefined但沒有解決方案適用于我的型別。
type Options = {
id: number,
text: string | undefined,
properties: {
title: string,
subtitle: string | undefined,
}
}
type DefaultProperties = Pick<Options, "properties">;
// Try #1: does not work
type Type1 = NonNullable<DefaultProperties>;
// Try #2: does not work
type NotOptional<Type> = {
[Property in keyof Type]-?: Type[Property];
};
type Type2 = NotOptional<DefaultProperties>;
// Try #3: does not work
type Type3 = Exclude<Options, undefined>;
示例: TypeScript Playground
如何undefined從所有型別聯合型別中洗掉所有s?
編輯:
所有undefineds 都應該從我的型別中洗掉。例如:
Options['text'] : string(沒有了undefined)Options['properties']['subtitle'] : string(沒有了undefined)
后來我想為此使用該型別(例如):
const options : Options = { ... };
const defaults: DefaultProperties= { ... }; // With no undefined
const node : HTMLElement = .... ;
node.innerHTML = options.properties.subtitle !== undefined ? options.properties.subtitle : defaults.properties.subtitle;
當defaults.properties.subtitle具有型別時string | undefined,編譯器會拋出錯誤,因為innerHTML只允許strings. 為此,我想排除undefined.
uj5u.com熱心網友回復:
你真正貼近你的NotOptional實用型和Exclude,問題是,你定義DefaultProperties為一個物件properties的屬性,但你想洗掉undefined的DefaultProperties,而不是從它的properties屬性。
在評論中,您曾說過要DefaultProperties與propertieson保持相同的形狀Options。這意味著它的基本形狀(在我們嘗試洗掉之前undefined)是Options["properties"]。所以:
type NotOptional<Type> = {
[Property in keyof Type]: Exclude<Type[Property], undefined>;
};
type DefaultProperties = NotOptional<Options["properties"]>;
測驗:
const defaults1: DefaultProperties = {
title: "foo",
subtitle: undefined, // <== Error as desired
};
const defaults2: DefaultProperties = {
title: "foo",
subtitle: "something", // <== No error
};
游樂場鏈接
您還可以考慮洗掉可選性(結合您嘗試過的兩件事):
type NotOptional<Type> = {
[Property in keyof Type]-?: Exclude<Type[Property], undefined>;
};
type DefaultProperties = NotOptional<Options["properties"]>;
測驗:
const defaults1: DefaultProperties = {
title: "foo",
subtitle: undefined, // <== Error as desired (wrong type for `subtitle`)
};
const defaults2: DefaultProperties = { // <== Error as desired (missing `somethingElse`)
title: "foo",
subtitle: "something",
};
const defaults3: DefaultProperties = { // <== No error
title: "foo",
subtitle: "something", // <== No error
somethingElse: "x",
};
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/317152.html
標籤:打字稿
上一篇:替換對按鍵事件不起作用的符號
