[英]Index signature of type 'string' on interface not recognized (typescript)
[英]Passing an interface as a type with index signature in typescript
我希望能够将接口传递给Typescript中的某个函数,该函数可以接受任何对象类型,只要它的所有属性都属于某种类型即可。
考虑以下示例 :
function DoSomething(args: { readonly [propertyName: string]: string }) {
// do something
}
// MyArgs is really just a more strongly typed version of {[propertyName: string]: string}
interface MyArgs {
foo: string;
bar: string;
}
var someArgs: MyArgs = {
foo: "foo",
bar: "bar"
}
DoSomething({ foo: "foo", bar: "bar" }); // works
DoSomething(someArgs); // compile error: Index signature is missing in type 'MyArgs'
这是行不通的,因为someArgs
无法转换为用于函数参数的参数类型。
这与Typescript不同:由于只读修饰符, 类型中缺少了索引签名 ,这意味着DoSomething
函数无法正确地向args
添加新属性。 这意味着在对MyArgs
实例调用DoSomething
之后,它仍将遵循此接口签名。
我该如何在Typescript中表示呢? 还有其他我想念的方式吗?
如果属性类型兼容,则可以将对象文字类型分配给具有索引签名的类型,而接口类型则不可以。 看到这个评论 。 一旦你注释someArgs
类型MyArgs
的信息,这是一个对象文本丢失,只有MyArgs
类型用于检查可转让性的参数类型的DoSomething
。 readonly
修饰符无关紧要:问题是someArgs
是否满足TypeScript的(非常不完美)启发式的要求,因为它不太可能在传递给DoSomething
之前添加了非字符串属性。
为了使示例工作,您可以将MyArgs
更改为对象文字类型:
type MyArgs = {
foo: string;
bar: string;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.