Skip to content

Better IoC support #21531

Closed
Closed
@tinganho

Description

@tinganho

It would be nice if TS could be more IoC friendly. One of the main pains I have with it, is that it doesn't know an alternative constructor:

import { Component } from '@angular/component';

@Component({})
export class MyComponent {
    private a: string; // Error it is never initialized.
    ngOnInit() {
        this.a =  1
    }
}

Here we annotate a secondary constructor on IComponent:

interface IComponent {
    constructor ngOnInit?();
}

And then we instructs the class to implement it, note the use of implements keyword:

function Component(options: any) {
    return function<T extends Function>(_class: T implements IComponent): void {
         /*...*/
    }
}

And then, all people can be happy:

@Component({})
export class MyComponent {
    private a: string; // No error
    ngOnInit() {
        this.a =  1
    }
}

For property decorators, we currently face this problem:

@Component({})
export class MyComponent {
    @Input() a: string; // Error no init.
}

Here we introduce the initializes keyword:

function Component(options: any) {
    return function<T extends Function>(_class: T implements IComponent initializes @Input): void {
         /*...*/
    }
}

Other frameworks are built the other way around, instead of another disjoint function or class providing the construction of the class, a base class provides it. So we could theoretically write our component like below(if we disregard the class annotations ):

export class MyComponent extends BaseComponent {
    @Input() a: string;
    private b: string;
    ngOnInit() {
        this.b = ''; 
    }
}

And we should be able to achieve the same thing using a base class:

export class BaseComponent initializes @Input {
    constructor ngOnInit?(): void
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript vision

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions