簡體   English   中英

使用泛型檢查承諾時打字稿的怪異行為

[英]Weird behavior of typescript when checking a promise using generic type

我正在嘗試讓編譯器檢查Promise的類型,但是卻出現了奇怪的行為。 這是我嘗試過的4種不同的return選項:

interface MyResponse<T> {
  foo: number,
  data: T,
}

const g: () => Promise<MyResponse<number>> = async () => {

  // This behavior is fine, the compiler complains, as expected:
  // ERROR: Type 'string' is not assignable to type 'number'.
  return {
    foo: 1,
    data: 'wrong type'
  }

  // Both foo and data are missing, but I get no error. I don't get why
  return {}

  // data is missing, but still no error
  return {
    foo: 1
  }

  // Now the compiler complains about `data` being missing
  // ERROR: Property 'data' is missing in type '{ foo: number; bar: string;  }'.
  return {
    foo: 1,
    bar: 'this fails'
  }

}

值得注意的是,如果我不使用Promise (也不是async ),則會得到預期的錯誤。

知道為什么會這樣嗎?

[編輯]:這與應該由打字稿2.4修復的打字稿錯誤有關(請參閱github上的討論

在下一個版本發布之前,@ nitzan-tomer的答案仍然是一個不錯的解決方法。

當您稍微更改函數的簽名時,似乎可以解決此問題:

const g = async (): Promise<MyResponse<number>> => {
    ...
}

使用您的原始簽名會發生:

const g1 = async () => {
    return {}
}

const g2: () => Promise<MyResponse<number>> = g1

g1的類型為() => Promise<{}> ,編譯器認為可以將這種類型分配給() => Promise<MyResponse<number>>

它僅在返回值的結構與MyResponse的結構沖突時MyResponse


編輯

從2.4版開始解決此問題。
原始問題: 使用異步功能和通用類型時奇怪的檢查錯誤
與以下內容有關: Promise.then的通用參數推斷
已修復: 協方差檢查回調參數

暫無
暫無

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

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