限制参数函数的返回类型

3

我有一个以函数作为参数的函数,参数函数返回几个枚举中的一个。如何通过使用参数函数的返回类型来推断包装器函数的类型。

我认为通过下面的例子更容易理解:

const foo = { a: 1, b: '2' }

function h(k: (() => 'a' | 'b')) {
  return foo[k()]
}

const d = h(() => 'a') 
// expected: d should be of type number
//   actual: d is of type number | string

playground

2个回答

3
您可以将返回的键类型定义为通用参数(它将被推断为单个键而不是所有可能键的联合):
function h<K extends keyof typeof foo>(k: (() => K)) {
  return foo[k()]
}

const d = h(() => 'a') // now number

游乐场


1
发现了一个解决方法/解决方案,但不太美观。
function h<T extends (() => 'a' | 'b')>(k: T) {
  return foo[k()] as typeof foo[ReturnType<T>]
}

playground


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接