【发布时间】:2018-10-02 10:54:11
【问题描述】:
我需要函数来接收具有特定结构的接口的参数:它应该是字符串散列或字符串散列和属性字符串散列类型,如这些对象:
{
anotherHash: {
a: 'a',
b: 'b'
...
}
c: 'c',
d: 'd',
...
}
{
anotherHash: {
a: 'a',
b: 'b',
...
}
}
{
c: 'c',
d: 'd',
...
}
我尝试描述原语但没有成功
interface IStringHash {
[key: string]: string;
}
interface IModule {
anotherHash?: IStringHash;
[key: string]: string | IStringHash | undefined;
}
const myFunc(css: IModule): any => {...}
如果我尝试将具有真实接口的对象传递给函数,例如
interface IModule1 {
anotherHash: {
ala: string
};
foo: string,
bar: string
}
描述对象
const myObject: IModule1 = {
anotherHash: {
ala: 'boom'
}
foo: 'foo',
bar: 'bar'
}
它会抛出关于类型差异的错误:
Argument of type 'IModule1' is not assignable to parameter of type 'IModule'.
Index signature is missing in type 'IModule1'.
const myObject: IModule1
这里应该是元描述,但我不知道如何用打字稿表达它
这里是play
【问题讨论】:
-
你遇到了什么错误,它似乎有效(如果你有 strictNullChecks 你需要
string | IStringHash |undefined):typescriptlang.org/play/… -
“IModule1”类型的参数不可分配给“IModule”类型的参数。类型“IModule1”中缺少索引签名。
标签: typescript