打字稿:如何使用泛型定义引用对象的函数

Typescript: How to define a function that references an object using generics

如何使用泛型定义基于对象键的函数。实际用例有更多的键和值,所以我不想明确定义它。

const obj = {
    a: {
        1: 1,
        2: 2,
        3: 3,
    },
    b: {
        1:1,
        2:2,
        4:4
    },
};

// My best attempt
const fn = <T extends keyof typeof obj>(key1: T, key2: keyof T) => {
    return obj[key1][key2];
}

错误:Type 'keyof T' cannot be used to index type '{ a: { 1: number; 2: number; 3: number; }; b: { 1: number; 2: number; 4: number; }; }[T]'

您需要添加一些更通用的参数:

const obj = {
    a: {
        1: 1,
        2: 2,
        3: 3,
    },
    b: {
        1:1,
        2:2,
        4:4
    },
};

const fn = <O, T extends keyof O, U extends keyof O[T]>(o: O, key1: T, key2: U) => {
    return o[key1][key2];
}

fn(obj, 'a', 1) // ok
fn(obj, 'a', 6) // error

TS playground