Search code examples
typescripttypestypescript-types

Merging custom type with one from external library in Typescript


I have a type in an external library that looks like this:

export declare type CreateProductInput = {
    title: string;
}

I want this type to have another attribute so tried to add to it in my own index.d.ts file:

I have tried the following:

export declare type CreateProductInput = {
    subtitle: string;
}

But that did not work. I also tried the following:

declare module '@path/to/library/type/file' {
    declare interface CreateProductInput {
        subtitle: string;
    }
}

However, doing this overwrites the type completely and I no longer have access to the title field.

Can one merge types like this? Basically, I want to modify the original type by adding another property to it.


Solution

  • If you really want to stick with type then you should be able to do this even on an imported type:

    type a = {
        title: string
    }
    
    type b = a & {
        subtitle: string
    }
    
    const c: b = {
        title: "title",
        subtitle: "subtitle"
    }
    
    console.log(c)
    

    The other option would be to use an interface:

    type d = {
        title: string
    }
    
    interface e extends d  {
        subtitle: string
    }
    
    const f: e = {
        title: "title",
        subtitle: "subtitle"
    }
    
    console.log(f)
    

    Check out both in the playground. What you want to do with overwriting the type the way you're trying to do so isn't possible and is poor form. Create a new type/interface that has what you need.