typescript - 如何在 Typescript 中循环引用 keyof?
问题描述
我有以下类型:
type Test = {
[K in keyof Test]: string
}
我希望那K
是测试的关键。但我得到这个错误:Type parameter 'K' has a circular constraint
。我该如何解决?
更新
这种类型的使用如下:
type Settings = {
[K in keyof Settings]: string
}
type Items<T> = Record<keyof T, any>
function create(settings: Settings, data: Items<Settings>) {
}
create({
name: "tt"
}, {
name: "aaaa"
})
我想要数据参数中的类型推断create
解决方案
您可以定义Settings
为任意键的记录(使用预定义的 type PropertyKey = string | number | symbol
),其string
值:
type Settings = Record<PropertyKey, string>
保持Items
不变
type Items<T> = Record<keyof T, any>
并将通用参数添加到create
:
function create<S extends Settings>(settings: S, data: Items<S>) {
}
结果函数将接受data
与设置具有相同键的对象,否则抛出错误:
create({name: "tt", x: 'x'}, {name: 42, x: true}) // OK
create({name: "tt", x: 'x'}, {name: 42})
// ERROR: Property 'x' is missing in type '{ name: number; }' but required
// in type 'Items<{ name: string; x: string; }>
create({name: "tt", x: 'x'}, {name: 42, x: true, y: 1})
// ERROR: Object literal may only specify known properties, and 'y' does
// not exist in type 'Items<{ name: string; x: string; }>'.
data
可以通过添加通用键参数来支持属性的自动完成,这将允许部分data
对象:
type Items<K extends PropertyKey> = Record<K, any>
function create<S extends Settings, K extends keyof S>(settings: S, data: Items<K> ) {
}
create({name: "tt", x: 'x'}, {name: 42, x: true}) // OK
create({name: "tt", x: 'x'}, {name: 42}) // OK: data can omit properties
create({name: "tt", x: 'x'}, {name: 42, x: true, y: 1})
// ERROR: Object literal may only specify known properties, and 'y' does
// not exist in type 'Items<{ name: string; x: string; }>'.
推荐阅读
- php - 从 php 调用 ImageMagick 会产生“UnableToOpenModuleFile”
- c++ - 为什么当我在向量中输入相同的元素时向量会调整其大小
- prolog - 使用 prolog 在树中从通用开始和结束节点进行路径搜索
- google-apps-script - 在谷歌表格中将单元格范围从一张纸复制到另一张纸
- node.js - Discord.js 负载平衡多重响应
- github - 使用 git-lfs 存储的笔记本的 Google Colab 徽章
- reactjs - 在 GraphQL 中,如何创建一个不区分大小写的查询,用于在搜索栏中查找名称?
- android - 我应该在 MainActivity 中创建一个 ViewModel 以便将 MutableLiveData 与 NavigationDrawer 一起使用吗?
- optimization - 将集合和索引定义为别名时出错
- mysql - mysqldump 与选择 *