How to define generic type 'has property' constrint without type definition?

107 views Asked by At

Suppose we have to implement the following:

export class Class1<T> {
    public constructor(param1: T) {
        param1.prop1 = 1; // TS error: T doesn't have property 'prop1'
    } 
}

Given that we're unable to inherit all possible param1 from a single base interface`class``, how to constrain the T?

I've tried T extends { prop1: number }, but it's an incorrect syntax for TS.

1

There are 1 answers

0
Alexander Abakumov On BEST ANSWER

The solution I've given in the question is correct:

export class Class1<T extends { prop1: number }> {
    public constructor(param1: T) {
        param1.prop1 = 1; // No TS error now
    } 
}

It seems I've had some issues with VS Code's built-in error checker.