1

Is it possible to have a type-hinted object initializer inside a constructor on a parent class? Ex:

class Model {
    modelField: string;
    constructor(initializer: SomeSpecialType){
        Object.assign(this, initializer);
    }
}

class User extends Model{
    email: string;
}

const user = new User({
    email: '...' // only get type hints for the email property
})

I know it is possible using a static method:

class Model{
    someField: string;
    static new<T extends Model>(this: new() => T, data: Omit<T, keyof Model>) {
        return Object.assign(new this, data);
    }
}

const user = User.new({
    email: 'some email'
})

I tried to use the same parameters inside the constructor but TS is telling me that the this keyword cannot be used in a constructor not generics can be used there.

Ionel Lupu
  • 2,695
  • 6
  • 29
  • 53

0 Answers0