Skip to content

Flow type information across *ngFor-like directives #10510

Closed

Description

@mhevery

Alternative proposal for the: Allow template local variables to publish type information so that IDEs can provide better completion

Thanks to @chuckjaz for the clever idea.

class Person {
    first: string;
    last:string;
}

class MyComp {
    items: string[];
    people: Person[];
}


/**
 * Assume we have template such as this:
 * <div *ngFor="let person of people; trackBy: foo">
 *   {{people.length}}{{item.first}}
 * </div>
 */

// These global variables are here only to flow the type information.
var _comp: MyComp;
var _peopleLetType = NgFor.extractTypeFromOf(_comp && _comp.people);

class MyComponentFactory{
    context: MyComp;
    ngFor: NgFor<typeof _peopleLetType> = new NgFor<typeof _peopleLetType>(new DivInnerFactory());
    create() {
        this.ngFor.of = this.context.people;
    }
}

class DivInnerFactory {
    context: NgForRow<typeof _peopleLetType>;
    text: string;
    create() {
        this.context.$implicit.first; // expected type OK because $implicit is Person
        this.context.$implicit.name;  // expected type error because $implicit is Person
    }
}

class NgForRow<T> {
    $implicit: T;
}

@Component({
    // we need some way to hint to the template generated which property to use for type extraction
    // and which static function to use with that property.
    typeTransformation: ['of', NgFor.extractTypeFromOf]
})
class NgFor<T>{
    @Input({typeTransform: NgFor.extractTypeFromOf})
    of: T[];
    constructor(factory: Factory) {}
    static extractTypeFromOf<T>(expr: T[]|Iterable<T>): T {return undefined;}
}

interface Factory {
    create();
}
interface Iterable<T> {}
function Component(a:any): Function { return null; }
function Input(a:any): Function { return null; }

Try it out in TypeScript playground.

Activity

  1. added
    area: core
    on Oct 5, 2016
  2. added
    feature
    on Oct 12, 2016
  3. chuckjaz commented on Oct 19, 2016

    @chuckjaz
    Contributor

    Closed in favor of #12398

  4. angular-automatic-lock-bot commented on Sep 10, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  5. locked and limited conversation to collaborators on Sep 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corefeaturefreq3: high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions