typescript - 类型以表示在 Typescript 中具有特定值类型的对象的键
问题描述
我有一个函数,它接受一个带有两个键的配置对象。这些值是对象中的键数组。
type 上的a
值Config
将从 type 的对象中删除T
,但b
需要以某种方式转换这些值,该方式仅对字符串值的键有效。
结果是一个函数,它将类型T
作为显式参数并返回一个对类型对象进行转换的函数T
:
interface Config<T extends Object, K extends keyof T> {
a?: K[] // keys to remove from T, this works fine
b?: K[] // keys to modify string value - want to constrain these
}
export function f<T extends Object>(config: Config<T, keyof T>): (row: T) => Partial<T> {
return function (row) {
// remove keys from config.a
// do something stringy with keys from config.b
}
}
它是这样称呼的:
const fn = f<SomeType>({ a: [...], b: [...] })
是否有某种方法可以b
将Config
接口限制为仅字符串值键?我尝试了所有我能想到的方法,但我尝试的大部分方法都产生了语法错误。我现在正在通过将字符串值强制为字符串来解决这个问题,因为类型系统不知道它们是字符串。有一个更好的方法吗?
解决方案
如果您不需要跟踪要删除/添加的键的实际联合,则可以K
从Config
. 从您的示例中,我认为不需要。
为了只获取特定类型的键,我们可以使用条件类型和映射类型:
interface Config<T extends Object> {
a?: (keyof T)[] // keys to remove from T, this works fine
b?: KeyOfValueType<T, string>[] // keys to modify string value - want to constrain these
}
type KeyOfValueType<T, TValue> = {[P in keyof T]: T[P] extends TValue ? P : never}[keyof T];
export function f<T extends Object>(config: Config<T>): (row: T) => Partial<T> {
return function (row) {
return null as any;
}
}
interface SomeType {
nr: number;
str: string
}
const fnOk = f<SomeType>({ a: ['nr'], b: ['str' ] })
const fnNok = f<SomeType>({ a: ['nr'], b: ['str', 'nr'] })
推荐阅读
- javascript - 根据条件选择随机函数
- xml - 有没有办法限制根 xml 元素名称应该与 XSD 文件中的相同?
- python - For循环在数据框中打印每个城市的最大值和最小值
- python - Pylint 检查 `src` 目录未在 `src/collect/` 目录中发现错误
- angular - Angular 库项目中的全局 CSS 变量
- django - AWS Beanstalk Django 无法连接到 RDS 实例,因为从 RDS 终端节点解析了错误的私有 IP
- eclipse - 黑色主题的 Eclipse 控制台文本颜色难以阅读
- firebase - 从颤振模型自动生成firebase表
- string - 有没有办法在飞镖运行时分配/编辑 String[i][j] 值?
- python - 我正在尝试将 numpy.ndarray 转换为张量输入到我的模型