extending interface with generic in typescript

前端 未结 3 561
余生分开走
余生分开走 2020-12-15 22:56

I want to build an function which takes any object and return that object with few added properties. Something like:

    //this code doesn\'t work   
                


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-15 23:21

    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 & {    // '{}' can be replaced with 'any'
        on(): void
        off(): void
    };
    
    interface ISomething {
        someValue: number
    }
    
    var extendedType: IPropertiesToAdd = {
        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.

提交回复
热议问题