Home > Software engineering >  Extend type to add rest parameter
Extend type to add rest parameter

Time:01-03

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

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.

CodePudding user response:

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

  • Related