typescript - 使用其他参数作为键的函数中的类型检查对象参数
问题描述
我想创建一个接受三个参数的函数:对象、对象上的键和新值。我希望该函数能够使用 key 参数访问一个值,根据该数据执行一些操作,然后将属性设置为新值。
这是我最初采用的方法:
function someOperation(obj: object, key: keyof obj, newValue: typeof obj[key])
const obj = { a: 'hello', b: 2 };
// TypeScript should show an error unless the third parameter here is a string
someOperation(obj, 'a', 'goodbye');
console.log(obj); // should be { a: 'goodbye', b: 2 }
不幸的是,我在指定newValue
. 我可以将其类型设置为any
来修复错误,但我真的想要更强大的类型检查。有人对我如何解决这个问题有任何想法吗?也许有不同的方法来解决这个问题。谢谢。
解决方案
@zixiCat 的解决方案完全有效并且有效。但这似乎有些牵强,并且很难调试错误消息,例如
Argument of type '["a", "1"]' is not assignable to parameter of type 'TParams<{ a: number; b: string; }>'.
Type '["a", "1"]' is not assignable to type '["a", number]'.
Type 'string' is not assignable to type 'number'.(2345)
对于“更友好”的错误,可能有更优雅、更简单的解决方案。
function someOperation<T extends {}, K extends keyof T>(
obj: T,
key: K,
value: T[K]
) {
//
}
const test = { a: 1, b: '1' };
someOperation(test, 'a', 1); // OK
someOperation(test, 'b', '1'); // OK
someOperation(test, 'a', '1'); // Error
someOperation(test, 'c', '1'); // Error
推荐阅读
- javascript - 将点击事件添加到动态生成的html
- android - 在 Android Studio 中构建旧项目的问题
- python - 计算具有独特条件的熊猫的加权平均值
- java - 从java运行python脚本:CreateProcess error=2,系统找不到指定的文件
- java - 决定在 Spring Boot 应用程序中使用多个实现中的哪一个
- scala - 单独散列列类型 Array[Int] 的内容
- kubernetes - gcsfuse 在 GKE 和/或 python3 boto 中安装存储桶以进行流式写入?
- linux - 逐个搜索目录(以及任何子目录)中的每个文件
- php - 使用 ID 基于 php 参数执行 2 个 DB2 合并
- javascript - 用于多个用户模型的环回护照-facebook