如何为映射类型添加索引签名?

时间:2017-11-24 00:09:52

标签: typescript mapped-types index-signature

假设我有界面

interface X {
   a: string;
   b: number;
   c: boolean;
}

和一个功能

function values(x: X) {
   return Object.keys(x).map(s => x[s])
}

当我启用typescript的strict标志时,我得到错误“元素隐式具有'任何'类型,因为类型'X'没有索引签名”。因此,为了使其明确,我可以在X

的定义中添加索引签名
[key: string]: any;

轻松自负。

但是,如果I X现在是一个映射类型:

type X<T> = {
  [P in keyof T]: string;
}

我有功能

function values<T>(x: X<T>) {
  return Object.keys(x).map(s => x[s])
}

我应该在哪里添加索引签名?有没有办法明确这一点而不诉诸于像Object.keys(x).map(s => (x as any)[s])

这样的事情

1 个答案:

答案 0 :(得分:8)

你可以:

interface X {
    a: string;
    b: number;
    c: boolean;
    [key: string]: X[keyof X];
}

X[keyof X]的结果现在为(string | number | boolean),效果甚至优于any,因为您的函数返回(string | number | boolean)[]

Example

这两个例子的另一种方法是:

function values(x: X) {
    const keys = Object.keys(x) as (keyof X)[];
    return keys.map(s => x[s]);
}

不漂亮,但至少比(x as any)打字更多。

当然它也可以是通用的:

function values<T>(x: T) {
    const keys = Object.keys(x) as (keyof T)[];
    return keys.map(s => x[s]);
}
相关问题