I am brand new to typescript, and I have two classes. In the parent class I have:
abstract class Component {
public deps: any = {};
public props: any = {
Add a type to your variable and then return.
Eg:
const myVariable : string [] = ['hello', 'there'];
const result = myVaraible.map(x=> {
return
{
x.id
}
});
=> Important part is adding the string[] type etc:
I think what you want is:
abstract class Component {
public deps: any = {};
public props: any = {};
public makePropSetter<T>(prop: string): (val: T) => T {
return function(val) {
this.props[prop] = val
return val
}
}
}
class Post extends Component {
public toggleBody: (val: boolean) => boolean;
constructor () {
super()
this.toggleBody = this.makePropSetter<boolean>('showFullBody')
}
showMore (): boolean {
return this.toggleBody(true)
}
showLess (): boolean {
return this.toggleBody(false)
}
}
The important change is in setProp
(i.e., makePropSetter
in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.
The <T>
on makePropSetter
allows you to lock that function in to a specific type. The <boolean>
in the subclass's constructor is actually optional. Since you're assigning to toggleBody
, and that already has the type fully specified, the TS compiler will be able to work it out on its own.
Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody
respect that same signature.