extending interface with generic in typescript

You can create a new type alias which will allow your object to inherit the features of another object type. I found this bit of code here.

type IPropertiesToAdd<T extends {}> = T & {    // '{}' can be replaced with 'any'
    on(): void
    off(): void
};

interface ISomething {
    someValue: number
}

var extendedType: IPropertiesToAdd<ISomething> = {
    on(): void {
        console.log("switched on");
    },
    off(): void {
        console.log("switched off");
    },
    someValue: 1234,
};

I’ve tested this, and it seems that ‘T’ can be an interface, class, and an array type. I couldn’t get union types to work.

This only works on anonymous objects, it can’t be used for actual inheritance purposes.

Hope this helps.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)