I am working on a function that filters an array of objects based on their type
property:
export const retrieveLayoutChangeActions = (data: GetOperations['included']) =>
data.filter(d => d.type === 'layoutChangeAction') as LayoutChangeAction[];
The data
parameter could potentially contain other types besides just LayoutChangeAction[]
, such as (LayoutChangeAction | Product)[]
. How can I update the type definition to accommodate any type as long as it includes LayoutChangeAction
?
I attempted to use generics,
export const retrieveLayoutChangeActions = <T extends LayoutChangeAction>(data: T[]) =>
data.filter(d => d.type === 'layoutChangeAction') as LayoutChangeAction[];
However, this approach resulted in a
TS2345: Argument of type '(LayoutChangeAction | Product)[]' is not assignable to parameter of type 'LayoutChangeAction[]'.
Although the type definitions are complex, the property that distinguishes each type is as follows:
interface LayoutChangeAction extends BaseResponse<'layoutChangeAction'> {
type: 'layoutChangeAction';
/* unique attributes... */
}
interface Product extends BaseResponse<'product'> {
type: 'product';
/* unique attributes... */
}