[英]How to describe in generics object interface in Typescript?
I have objects like this:我有这样的对象:
{
classNames: {
foo: 'foo',
....
bar: 'bar'
},
method1: () => {....},
method2: () => {....},
stringKey1: 'stringKey1',
...
stringKeyN: 'stringKeyN',
}
I need to describe a function parameter for function我需要为函数描述一个函数参数
function func1(myObj) { ... }
My description has failed我的描述失败
interface IMyObject {
classNames: [key: string]: string;
method1: Function;
method2: Function;
[key: string]: string | undefined;
}
errors:错误:
Your problem is caused by attempting to specify the indexed type alongside "exceptions" to that type.您的问题是由于尝试在该类型的“异常”旁边指定索引类型引起的。
If you look at the below code (which should be what you are after) - if the Example
interface had the index signature, it would conflict with the other members.如果您查看下面的代码(这应该是您所追求的) - 如果
Example
接口具有索引签名,它将与其他成员发生冲突。 For example method1
doesn't conform to this: [index: string]: string;
例如
method1
不符合这个: [index: string]: string;
interface Example {
classNames: { [index: string]: string; };
method1: () => void;
method2: () => void;
}
interface Example1 {
[index: string]: string;
}
type ExampleUnion = Example | Example1;
const x: ExampleUnion = {
classNames: {
foo: 'foo',
bar: 'bar'
},
method1: () => {},
method2: () => {},
stringKey1: 'stringKey1',
stringKeyN: 'stringKeyN',
}
Now this causes you issues on access, because the two interfaces are still in conflict.现在这会导致访问问题,因为这两个接口仍然存在冲突。 You could solve that with custom type guards, but a different shape would resolve all your problems in one go:
你可以用自定义类型保护来解决这个问题,但不同的形状可以一次性解决你的所有问题:
interface Example {
classNames: { [index: string]: string; };
propertyBag: { [index: string]: string; };
method1: () => void;
method2: () => void;
}
const x: Example = {
classNames: {
foo: 'foo',
bar: 'bar'
},
method1: () => {},
method2: () => { },
propertyBag: {
stringKey1: 'stringKey1',
stringKeyN: 'stringKeyN',
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.