Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extend type to add rest parameter

I have a type

export type baseEventType = {
    eName: string;
    mName: string;
    
};

and I would like to extend it to take a rest parameter

interface gEvent extends baseEventType {
    ...rest: any[]
}

which obviously won’t work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to use it in this way

export const save = ({ eName, mName, ...rest }: gEvent) => 

So is there a way to make that work. Obviously the following would work

export const save = (eName: string, mName: string, ...rest: any[]) => {

but I would prefer if I can do something similar to the other structure.

>Solution :

You ca add an index signature to the gEvent, but this will in effect disable type checking for the argument, letting you pass in even properties in baseEvetType with any type:

export type baseEventType = {
    eName: string;
    mName: string;
};
interface gEvent extends baseEventType {
    [name: string]: any;
}

export const save = ({ eName, mName, ...rest }: gEvent) => {

}

save({
  eName: 0 // eName is declared as string but we can pass number because of the index signature
})

Playground Link

Using an intesection type is probably a better idea here. This will do better when type checking the named properties:

type gEvent = baseEventType & {
    [name: string]: any;
}

export const save = ({ eName, mName, ...rest }: gEvent) => {

}

save({
  eName: 0, // error
  other: "", // ok
})

Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading