Reputation: 7172
I've got two classes. One is parent Model class. Another is its children, so that:
import { IModel } from '../shared'
export default class DataModel implements IModel {
private data: {[key: string]: any} = {}
public constructor(data: {[key: string]: any}) {
this.data = data
}
// ... other methods
public forRequest = (params?: {[key: string]: any}): object => {
return {
...this.data,
...params
}
}
}
and
import { IModel } from '../shared'
import DataModel from './_'
export default class LoginModel extends DataModel implements IModel {
constructor() {
super({
email: '[email protected]',
password: 'test1234'
})
}
public forRequest = (): object => {
return super.forRequest({
sso: true
})
}
}
and:
export interface IModel {
forRequest(params?: {[key: string]: any}): object
...
}
Following the https://www.typescriptlang.org/docs/handbook/classes.html and example with animals, I would like to call my forRequest()
method, passing parameters to the parent class.
However, when I am calling super.forRequest(...)
I am getting error: Only public and protected methods of the base class are accessible via the 'super' keyword.ts(2340) .
(I have no problem to overload forRequest() method in parent class if this could be a solution, if necessary but not sure if this is such a good idea). (in IModel I tried in both ways, with params and without)
I am wondering what is different here than on the example from TS site, and why the code does not work.
Any help appreciated. Thank you.
Upvotes: 2
Views: 324
Reputation: 111
The difference here is with the way you declare your forRequest
function.
You're assigning a function as the value of the forRequest
property as opposed to assigning it to the prototype.
You only have access to super
in the child methods.
You should have access if you did this instead.
class DataModel {
private data: {[key: string]: any} = {}
public constructor(data: {[key: string]: any}) {
this.data = data
}
// ... other methods
public forRequest(params?: {[key: string]: any}): object {
return {
...this.data,
...params
}
}
}
class LoginModel extends DataModel {
constructor() {
super({
email: '[email protected]',
password: 'test1234'
})
}
public forRequest(): object {
return super.forRequest({
sso: true
})
}
}
See what it compiles to here
Upvotes: 2