I have been trying to comprehend inheritance in typescript
class user {
name: string;
email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
checkUserData = id => {
console.log(
"This user name is" +
this.name +
"his email address is" +
this.email +
"and his ID is" +
id
);
};
}
class college extends user {
id: number;
constructor(name, email, id) {
super(name, email);
this.id = id;
}
checkUserData = () => {
super.checkUserData(this.id);
};
}
let newUser: user = new college("Rohit Bhatia", "[email protected]", 4556);
console.log(newUser.checkUserData());
This is my code, Here I am getting following error
index.ts:31:11 - error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword.
31 super.checkUserData(this.id); ~~~~~~~~~~~~~
index.ts:37:13 - error TS2554: Expected 1 arguments, but got 0.
37 console.log(newUser.checkUserData()); ~~~~~~~~~~~~~~~~~~~~~~~
index.ts:10:19 10 checkUserData = id => { ~~ An argument for 'id' was not provide
In my code, I don't see use of private method so why am I getting that error? Also, I know there is so much wrong in my code, Can someone help me fixing it?
What are my intentions?
Inherting class user, creating a new property checkUserData in parent class (considering this as a common class) which takes ID as a parameter, Calling that class from one its child and passing id to it.
checkUserDataa function-valued property instead of a method. They are different. TrycheckUserData(id: number) { /* impl */ }instead ofcheckUserData = id => { /* impl */ }.newUserasuserand then try to call itscheckUserData()method with no argument, becauseuser.checkUserData()takes an argument. You need to annotate it aslet newUser: collegeor justlet newUser = new college(...). Once you widennewUserfromcollegetouser, the compiler has no idea that it is acollegeanymore and won't let you callcollege-specific methods.