Home > Blockchain >  In TypeScript, How do I go about adding a property to an object type in an Interface?
In TypeScript, How do I go about adding a property to an object type in an Interface?

Time:08-05

I am trying to understand how to merge declare an interface, but instead of adding a field to the interface itself, I wish to add a property to the object literal type.

I have a type defined in a library as follows:

interface DefaultSession {
    user?: {
      name?: string | null;
      email?: string | null;
      image?: string | null;
    };
    expires: ISODateString;
}

I know that if I wanted to add a field to this interface without changing the name, I could simply reopen and declare:

interface DefaultSession {
    role?: string
}

I have been studying the Typescript Handbook, but I can't find a way to merge declare role as a property under user to yield a type as follows:

interface DefaultSession {
    user?: {
        name?: string | null;
        email?: string | null;
        image?: string | null;
        role?: string | null;
    };
    expires: ISODateString;
}

CodePudding user response:

What you are looking for is intersection type:

enter image description here

  • Related