【问题标题】:How to describe an interface that should accept different interfaces of a certain structure?如何描述一个应该接受某种结构的不同接口的接口?
【发布时间】:2018-10-02 10:54:11
【问题描述】:

我需要函数来接收具有特定结构的接口的参数:它应该是字符串散列或字符串散列和属性字符串散列类型,如这些对象:

{
  anotherHash: {
    a: 'a',
    b: 'b'
    ...
  }
  c: 'c',
  d: 'd',
  ...
}

{
  anotherHash: {
    a: 'a',
    b: 'b',
    ...
  }
}

{
  c: 'c',
  d: 'd',
  ...
}

我尝试描述原语但没有成功

interface IStringHash {
    [key: string]: string;
}

interface IModule {
    anotherHash?: IStringHash;
    [key: string]: string | IStringHash | undefined;
}

const myFunc(css: IModule): any => {...}

如果我尝试将具有真实接口的对象传递给函数,例如

interface IModule1 {
    anotherHash: {
      ala: string
    };
    foo: string,
    bar: string
}

描述对象

const myObject: IModule1 = {
  anotherHash: {
    ala: 'boom'
  }
  foo: 'foo',
  bar: 'bar'
}

它会抛出关于类型差异的错误:

Argument of type 'IModule1' is not assignable to parameter of type 'IModule'. Index signature is missing in type 'IModule1'. const myObject: IModule1

这里应该是元描述,但我不知道如何用打字稿表达它

这里是play

【问题讨论】:

  • 你遇到了什么错误,它似乎有效(如果你有 strictNullChecks 你需要string | IStringHash |undefined):typescriptlang.org/play/…
  • “IModule1”类型的参数不可分配给“IModule”类型的参数。类型“IModule1”中缺少索引签名。

标签: typescript


【解决方案1】:

IModule 和 IStringHash 都定义了一个 string 索引器。这意味着可以使用任意字符串来访问属性,因此可以添加随机属性。 IModule1 不能通过任意键访问,它要求属性与指定的完全相同。

这是不兼容的根源。由于myFunc 可以使用随机的string 进行索引,因此它可能违反IModule1 的约束。如果我们直接传递一个对象字面量,我们就没有问题,因为对象字面量将被扩展为包含一个索引签名:

MyFunction({
    anotherHash: {
        ala: 'boom'
    },
    foo: 'foo',
    bar: 'bar'
});

我们可以给IModule1添加索引签名:

interface IModule1 {
    anotherHash: {
        [key: string]: string;
        ala: string
    };
    foo: string,
    bar: string,
    [key: string]: string | IStringHash | undefined;
}

const myObject: IModule1 = {
    anotherHash: {
        ala: 'boom'
    },
    foo: 'foo',
    bar: 'bar'
}

MyFunction(myObject)

不需要添加字符串索引的更复杂的方法是使用映射类型来表达约束:

type IStringHash<K extends string> = {
    [P in K]: string;
}

type IModule<T extends string, TOther extends string> = {
    [P in T]: "anotherHash" extends P ? IStringHash<TOther> : string;
}

const MyFunction = <T extends string, TOther extends string>(obj: IModule<T, TOther>): any => { 
    return "Hello World!"
}

interface IModule1 {
    anotherHash: {
        ala: string
    };
    foo: string,
    bar: string
}

const myObject: IModule1 = {
    anotherHash: {
        ala: 'boom'
    },
    foo: 'foo',
    bar: 'bar'
};

MyFunction(myObject)

【讨论】:

猜你喜欢
  • 2016-08-09
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 2010-12-13
  • 2010-09-19
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
相关资源
最近更新 更多