Converting the generic type to any is a valid approach (The type E could be a typescript type, class, or interface) of various entities like Product, Post, Todo, Customer, etc.:
function test<E>(o:E):string {
return (o as any)['property']
}
Is casting to any generally the best way to handle this situation?
The complete context was requested. Here's the entire function that is being implemented:
/**
*
* @param entities The entities to search
* @param exclude Keys to exclude from each entity
*
* @return E[] Array of entities with properties containing the search term.
*/
export function search<E extends WithProperty>(query:string='', entities:E[], exclude:string[]=[]) {
const { isArray } = Array
query = query.toLowerCase();
let keys:string[] = []
if (entities.length > 0) {
keys = excludeKeys(entities[0], exclude)
}
return entities.filter(function (e:E) {
return keys.some((key)=>{
const value = (e as any)[key];
if (isArray(value)) {
return value.some(v => {
return new String(v).toLowerCase().includes(query);
});
}
else if (!isArray(value)) {
return new String(value).toLowerCase().includes(query);
}
})
});
}
/**
* The method can be used to exclude keys from an instance
* of type `E`.
*
* We can use this to exclude values when searching an object.
*
* @param entity An instance of type E
* @param eclude The keys to exclude
*
*/
export function excludeKeys<E>(entity: E, exclude: string[]) {
const keys: string[] = Object.keys(entity);
return keys.filter((key) => {
return exclude.indexOf(key) < 0;
});
}