简体   繁体   English

如何在Typescript中的泛型对象接口中描述?

[英]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:错误:

  • Property 'classNames' of type '[any, string]' is not assignable to string index type 'string'. “[any, string]”类型的属性“classNames”不可分配给字符串索引类型“string”。
  • Property 'method1' of type 'Function' is not assignable to string index type 'string'. “Function”类型的属性“method1”不可分配给字符串索引类型“string”。
  • Property 'method2' of type 'Function' is not assignable to string index type 'string'. “Function”类型的属性“method2”不可分配给字符串索引类型“string”。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM