首页 > 解决方案 > 使用其他参数作为键的函数中的类型检查对象参数

问题描述

我想创建一个接受三个参数的函数:对象、对象上的键和新值。我希望该函数能够使用 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来修复错误,但我真的想要更强大的类型检查。有人对我如何解决这个问题有任何想法吗?也许有不同的方法来解决这个问题。谢谢。

标签: typescriptfunctionparameterstypechecking

解决方案


@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

操场


推荐阅读