typescript - 类型 'Key' 不能用于索引类型 'Object'

标签 typescript types typescript2.0

试图用声音类型实现功能性的弹奏,但我做错了:

function pluck<Object extends {}, Key = keyof Object>(key: Key): (o: Object) => Object[Key] {
  return object => object[key];
}

TS 错误:

Type 'Key' cannot be used to index type 'Object'

最佳答案

你想要Key extends keyof Object:

function pluck<Object extends {}, Key extends keyof Object>(key: Key): (o: Object) => Object[Key] {
  return object => object[key];
}

泛型中的语法 T = S 指定类型的默认值,但不以任何方式限制类型。

关于typescript - 类型 'Key' 不能用于索引类型 'Object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46846669/

相关文章:

TypeScript 编译器 API : how to get literal value by ImportSpecifier node?

reactjs - GitHub Primer React组件与Octions的结合使用

javascript - 删除周六和周日,仅获取该月中的几天

visual-studio - 使用 TypeScript 2.1 使 @types 在 Visual Studio 2015 Update 3 中工作

typescript - 如何将 "keyof T"表示为 String 的子集?

swift - 创建一个 [字符串 : Class] dictionary in Swift 4

haskell - 将有效的 forall 类型归因于 let-bound 变量时出现类型错误

types - 标准 ML 二叉树类型

typescript - 在 typescript 2.0 中搜索类型定义的规范方法

typescript - 使用严格的空检查处理 Typescript 2.0 中的数组移位返回类型