如何在Typescript中添加属性类型?

2exbekwf  于 2022-12-24  发布在  TypeScript
关注(0)|答案(1)|浏览(145)

我有这个密码

type WithRequiredProperty<Type, Key extends keyof Type> = Omit<Type, Key> & {
    [Property in Key]-?: Type[Property];
};

export type MessageWithMdEnforced = WithRequiredProperty<IMessage, 'md'>;
export interface IMessage extends IClass {
    rid: RoomID;
    msg: string;
    tmid?: string;
    tshow?: boolean;
    ts: Date;
}

问题是IMessage是从node_modules导入的,因此我无法在node_modules中进行更改。我想在IMessage接口中添加errorReason: string类型
有谁能告诉我该怎么做?如何实现这一目标?

z9smfwbn

z9smfwbn1#

您只需要创建一个由IMessage扩展的新接口,这样新接口就可以继承这些属性并使用新接口

type WithRequiredProperty<Type, Key extends keyof Type> = Omit<Type, Key> & {
    [Property in Key]-?: Type[Property];
};

interface NewMessage extends IMessage {
    errorReason?: string;
} 

export type MessageWithMdEnforced = WithRequiredProperty<NewMessage, 'md'>;

相关问题