繁体   English   中英

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

[英]How to describe in generics object interface in Typescript?

我有这样的对象:

{
  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”。
  • “Function”类型的属性“method2”不可分配给字符串索引类型“string”。

您的问题是由于尝试在该类型的“异常”旁边指定索引类型引起的。

如果您查看下面的代码(这应该是您所追求的) - 如果Example接口具有索引签名,它将与其他成员发生冲突。 例如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',
}

现在这会导致访问问题,因为这两个接口仍然存在冲突。 可以用自定义类型保护解决这个问题,但不同的形状可以一次性解决你的所有问题:

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