如何在Typescript中的泛型对象接口中进行描述?
我有这样的物体:如何在Typescript中的泛型对象接口中进行描述?,typescript,Typescript,我有这样的物体: { classNames: { foo: 'foo', .... bar: 'bar' }, method1: () => {....}, method2: () => {....}, stringKey1: 'stringKey1', ... stringKeyN: 'stringKeyN', } 我需要为函数描述一个函数参数 function func1(myObj) { ... } 我的描述失败了 int
{
classNames: {
foo: 'foo',
....
bar: 'bar'
},
method1: () => {....},
method2: () => {....},
stringKey1: 'stringKey1',
...
stringKeyN: 'stringKeyN',
}
我需要为函数描述一个函数参数
function func1(myObj) { ... }
我的描述失败了
interface IMyObject {
classNames: [key: string]: string;
method1: Function;
method2: Function;
[key: string]: string | undefined;
}
错误:
- 类型为“[any,string]”的属性“classNames”不可分配给 字符串索引类型“string”
- 类型为“Function”的属性“method1”为 不可分配给字符串索引类型“string”
- 属性“method2” 类型“函数”不可分配给字符串索引类型“字符串”
示例
接口具有索引签名,它将与其他成员冲突。例如method1
不符合以下要求:[索引:字符串]:字符串代码>
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',
}
现在,这会导致访问问题,因为这两个接口仍然存在冲突。您可以使用自定义类型的防护装置解决此问题,但不同的形状可以一次性解决所有问题:
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',
}
}
您想要什么?未明确在TypeScript中描述此类对象只需为您的对象创建一个接口请,尝试-我尝试过但没有成功请查看有关的指导原则以及什么构成了。感谢您的回答,但我无法将字符串键从对象的根(stringKey1…stringKeyN)移动到键(