首页 > 解决方案 > 类型以表示在 Typescript 中具有特定值类型的对象的键

问题描述

我有一个函数,它接受一个带有两个键的配置对象。这些值是对象中的键数组。

type 上的aConfig将从 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: [...] })

是否有某种方法可以bConfig接口限制为仅字符串值键?我尝试了所有我能想到的方法,但我尝试的大部分方法都产生了语法错误。我现在正在通过将字符串值强制为字符串来解决这个问题,因为类型系统不知道它们是字符串。有一个更好的方法吗?

标签: typescriptgenerics

解决方案


如果您不需要跟踪要删除/添加的键的实际联合,则可以KConfig. 从您的示例中,我认为不需要。

为了只获取特定类型的键,我们可以使用条件类型和映射类型:

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'] })

推荐阅读