我不知道這是否sub interface是正確的術語,但是,我想做的是,我想創建一個介面,除了一些可選的屬性之外,它具有超級介面的所有屬性。我一直在查看介面的 Typescript 檔案,但找不到我需要的東西。
我知道這可以通過復制粘貼除子界面中我不super Interface想要的那些之外的每個道具來實作,但是,我不想要這種方法,因為我的用例基本上包裝了一個需要引數的函式type ,但在傳遞它們之前洗掉了一些可選屬性。為了更容易理解,我將留下一個簡單的例子。T
interface DefaultParams {
param1: boolean;
param2: boolean;
param3?: boolean;
... // and lots of other properties that are coming from the library which I want to include
}
// notice that there is no 'param3' in SubParams interface
interface SubParams {
param1: boolean;
param2: boolean;
... // and lots of other properties that are coming from the library which I want to include
}
type InnerFunction = (params: DefaultParams) => void;
const funcToCall: InnerFunction = thirdPartyLibrary.function;
function wrapperFunction(params: SubParams) {
funcToCall(params);
}
基本上我正在尋找的是創建一個SubParams完全兼容的介面,DefaultParams但它不會在其中包含param3可選屬性。
這是我在 Stackoverflow 上的第一個問題,如果有任何遺漏或錯誤,我將不勝感激。
uj5u.com熱心網友回復:
Omit例如,您可以使用
interface User {
name: string;
age: number;
gender: "F" | "M";
phoneNumber: string;
}
interface UserProfile extends Omit<User, "phoneNumber"> {
address: string;
}
這意味著,如果變數設定為,則UserProfile該變數將具有name、age和沒有。genderaddressphoneNumber
這是供參考https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys
省略<型別,鍵>
通過從 Type 中選擇所有屬性然后洗掉 Keys(字串文字或字串文字的聯合)來構造一個型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436898.html
標籤:打字稿
上一篇:TypeScript:從其他字串文字聯合型別中限制鑒別聯合中的鑒別器
下一篇:為什么“字串”不能用于索引?
