如何用keyof键入嵌套属性?

时间:2017-01-17 11:00:44

标签: typescript

我想更严格地输入这个方法:

function deepCompare(key: string, name: string, value: any) {
    return sources[key][name] === value;
}

我尝试使用keyof但未能使嵌套name工作:

type Sources = typeof sources;

function deepCompare<KSource extends keyof Sources, KName extends keyof Sources[KSource], T>(
    key: KSource,
    name: KName,
    value: Sources[KSource][KName],
 ) {
    return sources[key][name] === value;
 }

此调用应返回类型错误:“3不是字符串”

deepCompare("repo", "title", 3);

但我得到了"title" is not assignable to type 'never'

作为参考,这是目标对象:

const sources = {
    repo: {
        title: "hola",
        count: 3,
    },
    editing: {
        isDirty: false,
    },
};

0 个答案:

没有答案