0

I am trying to create a generic component which can expect data of two types only:

interface X{
    name: string,
    path: string,
    type: string,
}

interface Y{
    name: string,
    path: string,
}

Both types X,Y have two common properties and X has one extra. Now I am defining the type this way:

export class MyComponent<T extends X | Y> implements OnInit{
    @Input() data: T[];
    func(item: T){
        let temp = this.data.find(x => x.name === item.name);
        <<....some code....>>
    }
}

Calling this from the parent component this way:

<my-component [data]="xList"></my-component>     <!-- xList: X[] -->
<my-component [data]="yList"></my-component>     <!-- yList: y[] -->

This is working fine but I am not sure if this <T extends X | Y> is the correct way to do this or not. Can anybody please suggest the best approach here? Can we write something like where T implements X | Y in Typescript?

Or should I just use @Input() data: any[];?

2 Answers 2

1

I think this is fine but I would do T extends Y only because the type key is extra on the X and this component would break if we feed it an input of type array of Y and the component messes around with the type key.

Sign up to request clarification or add additional context in comments.

1 Comment

No, this component doesn't do anything with type key.
0

I don't think the Angular framework would know the generic argument T when it instantiate MyComponent. the only thing i can think of is to get an instance of the component at runtime and try to set the generic type yourself which will make any diffrence as the MyComponent would be instanciated already and the @Input() data would be set.

I think you should just write @Input() data: X[] | Y[].

1 Comment

@Input() data: X[] | Y[] would lead to error in this.data.find(x => x.name === item.name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.