我創建了一個基本模型類,其中包含傳入資料的模型,出于某些外部原因,我將在類內部對資料進行建模。盡管我遇到了將傳入資料定義到此模型類中的問題。這是我的課
export class EntityBasic {
constructor(
public id: string,
public title: string,
public urn?: string,
public risk_level?: string,
public be_aware?: string,
public body?: string,
public published_at?: string,
public created_at?: string,
public updated_at?: string,
public description?: string,
public notes?: string,
) {}}
}
我如何在另一個頁面中定義其中的內容:
public getEntity(setEntity) {
return new EntityBasic(
setEntity.id,
setEntity.title,
setEntity?.urn,
setEntity?.risk_level,
setEntity?.be_aware,
setEntity?.body,
setEntity?.published_at,
setEntity?.created_at,
setEntity?.updated_at,
setEntity?.report?.summary || '',
setEntity?.report?.metadata?.source_notes,
setEntity?.report?.metadata?.notes,
);
}
但是像這樣定義資料給我帶來了問題,因為有時不會有骨灰盒或 risk_level 例如,資料會在類中混亂。
我想要一種這樣定義的方法(這不起作用):
public getEntity(setEntity) {
return new EntityBasic(
id = setEntity.id,
title = setEntity.title,
urn = setEntity?.urn,
risk_level = setEntity?.risk_level,
)
}
uj5u.com熱心網友回復:
我相信將所有引數包裝到一個物件中是最好的解決方案。
- 將它們包裝為介面
interface EntityBasicParameters {
id: string;
title: string;
urn?: string;
risk_level?: string;
be_aware?: string;
body?: string;
published_at?: string;
created_at?: string;
updated_at?: string;
description?: string;
notes?: string;
}
- 僅接受此物件作為建構式引數
export class EntityBasic {
constructor(params: EntityBasicParameters) {}}
}
- 現在您只能傳遞現有資料
public getEntity(setEntity) {
return new EntityBasic({
id: setEntity.id,
title: setEntity.title,
urn: setEntity?.urn,
risk_level: setEntity?.risk_level,
})
}
要不就
public getEntity(setEntity) {
return new EntityBasic(setEntity)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352809.html
標籤:javascript 打字稿
下一篇:在ES6中更新物件陣列的重復值
