How to use type assertion on @input() variable?

Discussão em 'Angular' iniciado por Jake Zeitz, Outubro 30, 2024.

  1. Jake Zeitz

    Jake Zeitz Guest

    I have created a union type of several interfaces that share a common parent through inheritance. That union type is passed on to specific components. Those components will only ever be one of the child types. How can I assert the type on the child component?

    Example:

    interface Common {
    a: string;
    b: string;
    }

    interface Child1 extends Common {
    c: string;
    }

    interface Child2 extends Common {
    d: string;
    }

    type Union = Child1 | Child2;


    The parent component has a variable

    data: Union;


    and passes it to child components like so:

    <app-child1 [data]="data"></app-child1>
    <app-child2 [data]="data"></app-child2>


    The child component will only ever be one of those types so I should be able to assert it somehow:

    @Input() data: Child1;


    Currently this will throw a type error claiming Child1 is missing properties.

    I've tried these @Input() data: Union as Child1; and <app-child1 [data]="data as Child1"> but those just break.

    How can I assert this correctly?

    Continue reading...

Compartilhe esta Página