簡體   English   中英

如何從參數 object 動態推斷返回類型?

[英]How to dynamically infer return type from the argument object?

我正在嘗試為我的 TS 項目構建一個嚴格類型化的工廠,並且在確定是否可以從傳遞的參數中自動推斷模式時遇到問題。

type References = {
  [name: string]: any
}

function generateReferences<T extends string | number | symbol>(
  ref: References,
) {
  type Return = {
    [name in T]: string
  }

  return Object.keys(ref).reduce(
    (acc, name) => ({
      ...acc,
      [name]: `Hello from ${name}`,
    }),
    {},
  ) as Return
}

const cuteAnimals = generateReferences({
  rabbits: {},
  kittens: {},
})

console.log(cuteAnimals.rabbits)
console.log(cuteAnimals.kittens)
console.log(cuteAnimals.snakes) <!--- Should raise an error here

我正在嘗試基於輸入 object 實現動態返回類型整形。 相反,TS 威脅以簡單記錄的形式返回類型。

A 找到了一種解決方法,我可以將ref object 定義為單獨的變量並將其typeof作為模板參數傳遞,但我更希望 TS 根據輸入參數自動推斷形狀。

將不勝感激任何想法。

您應該縮小References類型而不是顯式聲明它:

type Return<K, V> = Record<keyof K, V>

function generateReferences<References>(
  ref: References,
) {
  return Object.keys(ref).reduce(
    (acc, name) => ({
      ...acc,
      [name]: `Hello from ${name}`,
    }),
    {} as Return<References, string>,
  )
}

const cuteAnimals = generateReferences({
  rabbits: {},
  kittens: {},
})

console.log(cuteAnimals.rabbits)
console.log(cuteAnimals.kittens)
console.log(cuteAnimals.snakes) // error

暫無
暫無

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

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