Chrillewoodz Chrillewoodz - 3 months ago 10
TypeScript Question

How to give a type to a property of this

ngOnInit() {

let isTest: boolean = this.isTest || false;

this.isTest: boolean = this.isTest || false;
}


Using
let
the compiled code becomes
var isTest = this.isTest || false
as you would expect but when assigning to
this
it becomes:

this.isTest;
boolean = this.isTest || true;


And also throws the error
boolean is not defined
, which makes sense.

What I don't understand however is why I can't define a type for a property of this
this
the way I'm doing it.

Why is this and what would be the correct way of doing it?

EDIT:

Apparently you can't declare class members inside methods, but would the same solution as @NitzanTomer gave apply for Angular 2's component input properties?

Example:

@Component({
selector: 'test',
inputs: [
'isTest'
]
})

export class isTest implements OnInit {
isTest: boolean;

ngOnInit() {
this.isTest = this.isTest || false;
}
}

Answer

You can't declare class members inside methods, it should be:

class YourClass {
    isTest: boolean;

    ngOnInit() {
        this.isTest = this.isTest || false;
    }

    ...
}

Edit

You can also declare class members in the constructor like this:

class YourClass {
    constructor(private isTest: boolean) { }
}

2nd Edit

I'm not an angular developer, but based on examples it seems that you need to do the same as I answered, just that you sometimes decorate those members with @Input.

For example:

@Component({
    selector: 'hero-child',
    template: `
        <h3>{{hero.name}} says:</h3>
        <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
    `
})
export class HeroChildComponent {
    @Input() hero: Hero;
    @Input('master') masterName: string;
}

Or:

@Component({
    selector: 'hero-parent',
    template: `
        <h2>{{master}} controls {{heroes.length}} heroes</h2>
        <hero-child *ngFor="let hero of heroes"
            [hero]="hero"
            [master]="master">
        </hero-child>
    `
})
export class HeroParentComponent {
    heroes = HEROES;
    master: string = 'Master';
}