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.
CodePudding user response:
Unfortunately, a type alias cannot be merged. That is one of the differences with an interface declaration in TypeScript.
But you can create a new interface that extends a type, although this does not seem what you want here:
type CreateProductInput = {
title: string;
}
interface CreateProductInput2 extends CreateProductInput {
subtitle: string;
}
declare const test: CreateProductInput2;
test.title; // Okay
test.subtitle;
For more details, see e.g. Interfaces vs Types in TypeScript
CodePudding user response:
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.