我正在嘗試更改物體的型別。我正在呼叫一個需要 2 個引數的函式,1 個是物體,另一個是位置。盡管當我嘗試為第一個物體傳遞 Type 時給了我這個錯誤:
Argument of type 'Node<EntityBasic>' is not assignable to parameter of type 'Node<AlertBasic>'.
Type 'EntityBasic' is not assignable to type 'AlertBasic'.
Property 'id' is optional in type 'EntityBasic' but required in type 'AlertBasic'.
這是函式:
public async func() {
const entBasic: EntityBasic = this.getEntity(entity);
const NEO4J_TYPE = entType === 'alert' ? 'Alert' : 'Guide';
const entNode = await this.neo4jService.createOrUpdate<EntityBasic>(
NEO4J_TYPE,
entBasic.id,
entBasic,
);
if (NEO4J_TYPE === 'Alert')
await this.calendarEventsSyncService.handleEvents(entNode, location);
}
我需要將 entNode 從 EntityBasic 更改為 AlertBasic
我曾嘗試:
if (NEO4J_TYPE === 'Alert')
await this.calendarEventsSyncService.handleEvents(entNode: AlertBasic, location);
但我得到一個 Expected 2 parameter instead of 3
uj5u.com熱心網友回復:
您可以投射entNode到Node<AlertBasic>:
await this.calendarEventsSyncService.handleEvents(entNode as Node<AlertBasic>, location);
或者在AlertBasic和之間的介面沖突的情況下EntityBasic:
await this.calendarEventsSyncService.handleEvents(entNode as unknown as Node<AlertBasic>, location);
uj5u.com熱心網友回復:
據我所知你只能entNode: AlertBasic用來宣告一個函式簽名。不是在呼叫函式時,這就是您正在做的事情。
if (NEO4J_TYPE === 'Alert')
await this.calendarEventsSyncService.handleEvents(entNode: AlertBasic, location);
有幾種方法可以解決這個問題,哪種方法合適實際上取決于更大的系統。
一個有風險的解決方案:用作
您可以使用as告訴 TypeScript 將一種型別偽裝成另一種型別。這可能會導致問題,因為您在系統中引入了謊言。
if (NEO4J_TYPE === 'Alert')
await this.calendarEventsSyncService.handleEvents(entNode as Node<AlertBasic>, location);
預先轉換型別
您可能希望使用函式將一種型別轉換為另一種型別。帶有如下簽名:
function transform_AlertBasic_toEntityBasic( alert_basic: AlertBasic ): EntityBasic {
// ... some code that makes the transformation
}
檢查是否有超型別
可能有一個超類涵蓋了您可以使用的兩種型別的 API。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/351074.html
標籤:javascript 打字稿
