【问题标题】:Add dynamic property to type alias with known properties将动态属性添加到具有已知属性的类型别名
【发布时间】:2020-03-11 23:21:58
【问题描述】:

我想定义一个这样的类型别名:

export type Context = object & {
    tag: string
}

在使用类型时,我还希望能够像这样动态添加属性:

常量上下文:上下文 = { 标签:'一些标签', 动态属性:1 }

我收到了这个错误(我完全理解):

对象字面量只能指定已知属性,并且 “上下文”类型中不存在“动态属性”。

有没有办法允许动态添加属性?

我试过了

export type Context = any & {
    tag: string
}

但是从 TS 编译器的角度来看,这将是有效的:

const context: Context = {
    //tag: 'some-tag', // tag is not set which shouldn't be allowed
    dynamicProperty: 1
}

TS Playground

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以简单地在Context 的类型声明中添加索引签名以允许更多键值对:

    export type Context = {
        tag: string,
        [k: string]: any;
    }
    

    TS Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多