添加动态属性以键入具有已知属性的别名

时间:2020-03-11 15:19:10

标签: typescript

我想这样定义类型别名:

export type Context = object & {
    tag: string
}

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

const上下文:Context = { 标签:“ some-tag”, dynamicProperty:1 }

我收到此错误(我完全理解):

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

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

我尝试过

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

1 个答案:

答案 0 :(得分:1)

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

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

TS Playground

相关问题