首页 > 解决方案 > 约束参数函数的返回类型

问题描述

我有一个以函数为参数的函数。参数函数返回几个枚举之一。如何使用参数函数的返回类型来推断包装函数的类型。

我认为作为一个例子更容易解释:

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

操场

标签: typescripttypescript-typingstypescript-generics

解决方案


您可以将返回的键类型定义为通用参数(它将被推断为单个键,而不是所有可能键的联合):

function h<K extends keyof typeof foo>(k: (() => K)) {
  return foo[k()]
}

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

操场


推荐阅读