簡體   English   中英

為什么 typescript 在直接使用類型時與在擴展中使用 generics 時表現不同?

[英]why typescript behaves differently when using the type directly vs using generics with extends?

我不明白為什么代碼在使用 generics 時表現不同。
該主題基於How to create a relation between parameters of a function? 的答案。

interface Data {
  a: number,
  b: { x: number, y: number}
}

type GetKeyValueTuples<T> = { [Key in keyof T]: [Key, T[Key]] }[keyof T];

function getChangedDataByProperty<T extends Data>(
  ...[data, changedProp, newPropValue]: [T, ...GetKeyValueTuples<T>]
) {
  if (changedProp === "b") {
    changedProp
    return {
      ...data,
      b: {
        // why this has number, a, b types?
        x: newPropValue.x,
        y: newPropValue.y,
      }
    }
  } else {
    return {
      ...data,
      x: newPropValue
    }
  }
}

// why this behaves differently than the abvove function?
function getChangedDataByProperty2(
  ...[data, changedProp, newPropValue]: [Data, ...GetKeyValueTuples<Data>]
) {
  if (changedProp === "b") {
    changedProp
    return {
      ...data,
      b: {
        x: newPropValue.x,
        y: newPropValue.y,
      }
    }
  } else {
    return {
      ...data,
      x: newPropValue
    }
  }
}

ts 游樂場

getChangedDataByProperty2()函數的rest 參數是可區分的聯合類型,自 TypeScript 4.6 以來,我們已經能夠將此類可區分的聯合解構為單獨的參數,以獲得您所看到的縮小行為,其中對可區分changedProp的檢查縮小了newPropValue的類型。

另一方面, getChangedDataByProperty()的 rest 參數是一個通用類型,它最終被限制為相同的可區分聯合類型。 無論出於何種原因,TypeScript 都不認為泛型類型是可區分聯合的可接受的判別式。 microsoft/TypeScript#50652上有一個關於此的問題,但它目前被標記為“需要調查”,所以沒有官方的說法來說明這是一個錯誤、設計限制,還是可以解釋為一個功能請求。 它也在積壓中,這意味着這樣的官方消息可能不會出現。

暫無
暫無

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

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