Typescript Generics
# help-with-other
k
Any typescript guru's want to help me confirm that this is the way to do generics in Typescript ? I've struggled to find a nice simple example.
Copy code
ts

class TestModelBase {
    colour?: string;
};

class SizeModel extends TestModelBase 
{
    size?: number;
}


export class TestServiceBase<TObject extends TestModelBase> {

    model? : TObject;

    getColor() {
        return this.model?.colour;
    }
}

export class TestSizeService extends TestServiceBase<SizeModel> {

    // override
    getColor(): string | undefined {
        return this.model?.colour;
    }

    getSize() : number | undefined {
        return this.model?.size;
    }
}
What i am aiming for in my code is a base "context" that will have some core functionality in it, including going off to the server to get things (via a repoisitory that i can then extend and pass in another 'repository' (of same basemodel type) that calls different server end points but gets the 'same' result types just for different things. any red flags, have i missed something in this pattern ?
r
in principal, i can't see anything wrong with it.. purely as a idea why undefined rather empty or say null.. (null is bad and means more testing but just asking in case there is a situation where it could or should be null)... can't think of one. but playing devils avocado Not a typescript guru.. just asking questions for my understanding
k
yeah - i tend towards null not sury why i did that here, but it was mainly to get an example up
i think in this instance
model?
* with the question mark *is implicitly
TObject | undefined
which is why the returns on those methods become valie | undefined.