要求对象的值具有某种类型而没有索引签名

时间:2018-03-02 14:09:01

标签: typescript

有没有办法要求对象的值都具有某种类型而不需要索引签名?类似于:playground

type I = {
    [key: string]: string | number;
};

interface Y {
    a: number;
}

const y: Y = {
    a: 99
}

// pass y here
function myFunction(i: I) {
  for (const key of Object.keys(i)) {
    // something that applies to both strings and numbers
  }
}

// fails to compile as y has no index signature
myFunction(y as I);

我宁愿避免使用any

1 个答案:

答案 0 :(得分:1)

我们可以使用映射类型强制参数只包含number|string类型的属性:

function myFunction<T>(i: T & Record<keyof T, number | string>) {
    for (const key of Object.keys(i)) {

    }
}

myFunction({
    a: 99,
    b: new Date()
}); // Error as expected

interface Y { a: number; b: number }
declare let y: Y;
myFunction(y); // OK

interface X { a: Date; b: number }
declare let x: X;
myFunction(x); // Error as expected