I would like my function to take any kind of objects but if the objet have a property 'id' making sure that is is either a string or a number.
Here is the minimal example:
interface FnItem {
id?: string | number;
};
function fn<T extends FnItem>(item: T, callback: (item: T) => void) {
console.log(item.id);
callback(item)
};
fn({ name: 'Michel' }, item => item.name);
fn({ name: 'Michel', id: 12 }, item => item.name);
It throws this error
Argument of type '{ name: string; }' is not assignable to parameter of type 'FnItem'.
Object literal may only specify known properties, and 'name' does not exist in type 'FnItem'
---
Property 'name' does not exist on type 'FnItem
fn<YourType>(). If you just want an interface then you don't need the generic. The signature can simple befn(item:FnItem)