在类构造函数中重写

时间:2019-06-05 19:31:13

标签: typescript class generics inheritance strict-mode

我有一个父类Form和一个子类UserForm,它扩展了Form。我希望能够: -在UserForm的构造函数中传递数据键值对象(并具有intellinsense只会使UserForm的字段失效) -将数据中的所有字段作为UserForm实例的属性

这必须处于严格模式下。

示例:

class UserForm extends Form{
    name: string;
    email: string;
    age: number;
}


const userForm = new UserForm({ // pass only fields from UserForm: name, age, email
    age: 23,
    random: 123 // error. GOOD
});

console.log(userForm.age); // this needs to print 23

我设法使其与下面的代码一起工作(也在this link处),但是我无法使其在严格模式下工作:

type Without<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type FormFields<T extends Form<T>> = Partial<Without<T, keyof Form<T>>>;

abstract class Form<T extends Form<T>> { 

    constructor(data: FormFields<T>) {
        Object.keys(data).forEach(field => {
            this[field] = data[field as keyof FormFields<T>];
        });
    }
}


class UserForm extends Form<UserForm>{
    name: string;
    email: string;
    age: number;
}


const userForm = new UserForm({
    age: 23,
    random: 123 // error. GOOD
})

如果您在操场上激活严格模式,您将在Element implicitly has an 'any' type because type 'Form<T>' has no index signature行获得this[field] = data[field as keyof FormFields<T>];

如何解决此问题?

0 个答案:

没有答案