[英]Typescript - Check an object has all interface properties
說我有一些界面:
export interface MyDocument {
id: string,
collection: string[];
}
然后,我創建一個新的(將現有類型強制轉換為該類型):
const workingDocument = <MyDocument>document;
最后,我有這個if語句塊來檢查它是否確實包含我在該接口中指定的所有內容:
if (!workingDocument.id) {
throw new Error("Document missing `id`");
} else if (!workingDocument.collection) {
throw new Error("Document missing `collection` array");
}
但是我似乎不喜歡這樣,如果語句可以永遠增長並且很難維護。
有沒有更好的辦法?
謝謝。
如果在內部創建/使用此Document類型,則可以使用類型/接口自己聲明其類型,而無需強制轉換。
但是,如果文檔來自您的打字稿應用程序外部,則需要進行某種形式的手動類型保護/檢查(要避免的事情)。
如果我理解正確,那么您正在要求運行時檢查對象是否包含接口定義的所有屬性。 單獨使用接口是不可能的,因為與接口關聯的類型信息不會使它進入運行時。 換句話說,該接口僅在我們運行TypeScript編譯器時才有用。
您可以做的是創建一個包含接口所有屬性的架構。 然后,您可以遍歷該架構以檢查所有屬性是否存在於您的對象上。 這是一個看起來如何的示例。 我已將示例包裝在用戶定義的類型guard中 。
export interface MyDocument {
id: string,
collection: string[];
}
const isMyDocument = (input: any): input is MyDocument => {
const schema: Record<keyof MyDocument, string> = {
id: 'string',
collection: 'array'
};
const missingProperties = Object.keys(schema)
.filter(key => input[key] === undefined)
.map(key => key as keyof MyDocument)
.map(key => new Error(`Document is missing ${key} ${schema[key]}`));
// throw the errors if you choose
return missingProperties.length === 0;
}
const obj = {};
if (isMyDocument(obj)) {
// the compiler now knows that obj has all of its properties
obj.collection;
}
這是TypeScript操場上的上述代碼。
這是使用...
運算符擴展架構的方法。
interface ParentDocument {
id: string,
collection: [],
}
interface ChildDocument extends ParentDocument {
name: string;
}
const schemaParent: Record<keyof ParentDocument, string> = {
id: 'string',
collection: 'array'
};
const schemaChild: Record<keyof ChildDocument, string> = {
name: 'string',
...schemaParent,
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.