Home > Back-end >  How to add type of property in Typescript?
How to add type of property in Typescript?

Time:12-22

I have this code

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;
}

The problem is that IMessage is imported from node_modules so I can not change in node_modules And I want to add errorReason: string type in IMessage interface

Can Anyone tell me what to do ? How to achieve this ?

CodePudding user response:

You just need to create new interface extended by IMessage so that the properties will be inherited to your new interface and use the new interface

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'>;
  • Related