簡體   English   中英

打字稿:“未知”類型的對象

[英]Typescript: Object of type 'unknown'

我有一個生成器函數foo() ,我在其中使用fetch調用API 收到來自API響應后,我將其解析為JSON

Typescript 拋出錯誤:此行Object of type 'unknown' -> const msg = yield response.json();

function* foo(val: ValType): Generator {
    const response = yield fetch(endPoint, {
        method: 'POST',
        body: JSON.stringify(val),
    });

    if (response) {
        // typescript throws error
        // that type is unknown for
        // the response object
        const msg = yield response.json();
        return msg;
    }
}

錯誤是因為您沒有為response聲明類型。 使用必須像這樣為 Generator 函數聲明類型。

function* foo(arg): Generator<YieldType, ReturnType, ArgType> {
  // 
}

不需要分別聲明 yield 類型、返回類型和參數類型,如果你這樣聲明,Typescript 可以推斷它們。

閱讀更多

暫無
暫無

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

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