打字稿索引访问,其中从同一接口的另一个属性查询索引

时间:2018-07-29 05:27:48

标签: typescript typescript-typings

一个例子演示了我的问题,比单词更好:

interface X {
    a: number,
    b: string
}

interface Y<T> {
    u: keyof T,
    v: T[this['u']]
}

const y: Y<X> = {
    u: 'a',
    v: 'this should be a number'
};

我希望v的类型基于u的值。我的意思是,如果u(应该是X的键)是 a ,那么我需要v的类型与{ {1}},即X.a。但是目前,number的类型为v,这是string | number中所有值类型的并集类型。

我可以使用当前的打字稿功能来实现吗?

1 个答案:

答案 0 :(得分:0)

您不能直接使用它,而需要一个额外的类型参数

interface X {
    a: number,
    b: string
}

interface Y<T, K extends keyof T> {
    u: K,
    v: T[this['u']] // or T[K]
}

const x: Y<X, 'a'> = {
    u: 'a',
    v: 0
};

为避免两次输入属性名称,可以使用一个函数来帮助创建。您需要一个返回函数的fi函数,因为Typescript尚不允许部分类型参数推断

function newY<T>() {
    return function <K extends keyof T>(p: Y<T, K>) {
        return p;
    }
}

let xx = newY<X>()({ u: 'a',v:0})