So I have a generic function, where argument array can be either of type Alfa[] or Beta[].
export interface Alfa {
id: number;
name: string;
propertyOne: string
propertyTwo: string
creation_date: string;
updation_date: string;
}
export interface Beta {
id: number;
propertyThree: string;
propetryFour: boolean;
creation_date: string;
updation_date: string;
}
import { isNil } from "lodash";
export const sort= <T>(array?: T | null) => {
if (isNil(array)) return;
return [...array].sort((a, b) => {
return Date.parse(b.creation_date) - Date.parse(a.creation_date);
});
};
So in if (isNil(array)) return;
I exclude null | undef, and when function iterates through array , I have an error: TS2461: Type 'T' is not an array type.
So, I tried :
export const sort= <T>(array?: ArrayLike<T> | null) => {
if (isNil(array)) return;
return [...array].sort((a, b) => {
return Date.parse(b.creation_date) - Date.parse(a.creation_date);
});
};
and here is another error: TS2461: Type 'ArrayLike' is not an array type.
So, how do I write a generic function?
CodePudding user response:
Your type hint does not guarantee that the "array" parameter is actually an array. Since you use a generic, I can pass any value in there, like a number, and it will pass the null check and try to spread that number, resulting in an error.
The way I would do it is to check if the parameter is an array instead of checking if it's not null, like this:
const sort = <T>(array?: T | null) => {
if (Array.isArray(array)) {
return [...array].sort((a, b) => Date.parse(b.creation_date) - Date.parse(a.creation_date));
};
return;
};
CodePudding user response:
Please try to use as follows:
export const sort= <Type>(array?: Type[] | null) => {
if (isNil(array)) return;
return [...array].sort((a, b) => {
return Date.parse(b.creation_date) - Date.parse(a.creation_date);
});
};
CodePudding user response:
Use T as the element type and write
export const sort= <T>(array?: T[] | null) => {
if (isNil(array)) return;
return [...array].sort((a, b) => {
return Date.parse(b.creation_date) - Date.parse(a.creation_date);
});
};