簡體   English   中英

鍵入'字符串 | undefined' 不可分配給類型 'string'

[英]Type 'string | undefined' is not assignable to type 'string'

我從 TypeScript 開始,遇到以下問題:

我有一個更新數據庫中記錄的方法,定義如下:

class Category {
  update (data: ICategory & { id: string }): Promise<ICategory & { id: string }> {
    // Do Stuff
  }
}

interface ICategory {
  id?: string
  name: string,
  icon: string,
  iconColor: string
}

請注意,接口中的 id 字段是可選的,並且該方法要求 id 為字符串,問題就出在這里:當我嘗試使用所述接口調用此方法時,出現以下錯誤:

TS2345: Argument of type 'ICategory' is not assignable to parameter of type 'ICategory & { id: string; }'.
  Type 'ICategory' is not assignable to type '{ id: string; }'.
    Types of property 'id' are incompatible.
      Type 'string | undefined' is not assignable to type 'string'.
        Type 'undefined' is not assignable to type 'string'.

即使我檢查typeof obj.id === 'string'我仍然有同樣的錯誤。

我怎么解決這個問題? 正如我所說,我現在從 TypeScript 開始,所以歡迎任何建議。

謝謝!

您可以為此使用Type Guard

interface FuncData {
    id: string;
}

function test(args: FuncData) { }

interface PartialData {
    id?: string;
}

const data: PartialData = { id: 'test' };

function funcDataGuard(data: PartialData): data is FuncData {
    return data.id != null;
}

if (funcDataGuard(data)) {
    test(data);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM