值具有类型的打字稿 keyof

Typescript keyof where value has type

我正在尝试用 Typescript 编写一个函数,它需要:

目前我的做法是:

function myFunction<
    T extends Record<K, boolean>, // the type of the object
    K extends keyof T, // the key which points to X
>(
    obj: T,
    objKey: K,
) {
    const x: boolean = obj[objKey];
}

只要我只需要对象的类型为 T 并且不需要其他类型,它就可以工作。但是,我现在需要一个同时实现 T(具有布尔成员的对象)和 AdditionalData 的对象。但是,如果我将 T extends Record<...> 替换为 T extends Record<...> & AdditionalData,类型检查当然会失败。

我想到的解决方案是引入另一种通用类型 L,它只包含来自 SomeInterface 的数据并使 K 依赖于此:

function myFunction<
    L extends Record<K, boolean>, // the type containing the boolean value
    K extends keyof L, // the key which points to X,
    T extends L & AdditionalData, // the type of the object
>(...) {}

然而,这也不起作用。

有什么方法可以强制键指向的值是特定类型的吗?

编辑:或者,有没有办法从 keyof 中排除特定值?这样,我就可以从 K...

中排除任何其他类型

Typescript 并不总是能很好地推断通用参数类型字段的类型。我不确定到底是什么导致它无法识别 obj[objKey]boolean 这一事实,但简单的解决方法是使用一个额外的变量:

interface AdditionalData {
    a: number,
    b: string
}

function myFunction<
    T extends Record<K, boolean> & AdditionalData, // the type of the object
    K extends keyof T, // the key which points to X
>(
    obj: T,
    objKey: K,
) {
    const o : Record<K, boolean>= obj; // assignable
    const x: boolean = o[objKey]; // access works ok
}