【问题标题】:Mapping proper type for interface property为接口属性映射正确的类型
【发布时间】:2021-08-15 12:52:15
【问题描述】:

我正在开发的模块 ( module1 ) 中有以下接口类型。

interface ModuleOneInterface {
    keyOne: customInterface;
    keyTwo: customInterface;
    keyThree: customInterface;
}

所以我目前正在开发第二个模块 (module2),它使用上述接口作为其组件中的道具。上面的接口不是从模块( module1 )导出的,因此我无法导入它( module2 )。我声明了另一个接口,它可以代表我的第二个模块( module2 )中的类型。下面是界面。

export interface ModuleTwoInterface {
    //This is the one which is accepting module one interface
    module2KeyOne: Record<string, customInterface>; 
    module2KeyTwo: string;
}

但这会引发以下错误。

TS2345: Argument of type 'ModuleOneInterface' is not assignable to parameter 
        of type 'Record<string, customInterface>'.

我在这里做错了什么?我也尝试了以下解决方案。但效果并不好。

interface moduleTwoSubInterface {
    [ key: string ]: customInterface;
}

export interface ModuleTwoInterface {
    // This is the one which is accepting module one interface
    module2KeyOne: moduleTwoSubInterface; 
    module2KeyTwo: string;
}

任何帮助将不胜感激。

【问题讨论】:

  • 如果ModuleOneInterface 已经被另一个外部模块使用,这似乎是一个很好的导出它的动力,不是吗?包很少会省略类型,通常甚至是私有/内部类型,因为类型系统的重点是让您的模块更容易开发。

标签: typescript typescript-typings react-typescript


【解决方案1】:

typeinterface大多数时间可以互换,但并非总是如此。

没有索引签名的接口不会扩展任何带有索引签名的东西,因此不能分配给它。
另一方面,类型别名确实扩展了具有索引签名的任何目标类型(使用typeinterface),当且仅当其所有属性都符合索引签名时。 IE。如果索引签名从stringFoo,则其所有属性都必须能够扩展Foo

这是操场上的一个最小示例:link

【讨论】:

    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2014-10-10
    • 2018-03-22
    相关资源
    最近更新 更多