具有索引签名的返回不同类型的键

时间:2018-07-18 21:49:06

标签: typescript keyof

当我有一个带有索引签名的接口时,我对keyof的工作方式感到困惑。

例如,如果我具有如下界面:

interface InterfaceOne {
  [id: string]: InterfaceOne[keyof InterfaceOne];
  a: SomeTypeOne;
  b: SomeTypeTwo;
}

我想要一个函数,其参数只能是InterfaceOne的有效属性,例如:

function test = (param: keyof InterfaceOne) => any

在上面的函数中,我应该能够调用test('a')test('b'),但是test('c')会导致编译错误,因为c不是{ {1}}。

当我在InterfaceOne中具有索引签名时,这似乎不起作用。

InterfaceOne返回type myType = keyof InterfaceOne。如果删除索引签名,它将按预期返回string | number

有人可以解释为什么添加索引签名会更改"a" | "b"返回的类型吗?另外,我可以强制参数为keyof属性名称的正确方法是什么?

0 个答案:

没有答案
相关问题