简体   繁体   中英

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'.
  • Property 'method1' of type 'Function' is not assignable to string index type 'string'.
  • Property 'method2' of type 'Function' is not assignable to string index type '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. For example method1 doesn't conform to this: [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',
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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