Let´s assume I have two interfaces.
interface AppleReport {
name: string,
color: string,
age: string
}
interface BananaReport {
name: string,
color: string,
amount: number,
}
Now I define a function. I want this function to take every type that has a name key and a color key.
cosnt doSth = (value: **TODO**) => {
// do sth with *value* that contains *name* and *color*
}
I know, that I could create an interface
interface dummyInterface {
name: string,
color: string,
}
and let the AppleReport and BananaReport extend this, but I would like to do all of the logic in the function type definiton.
Any ideas?
You could do
cosnt doSth = (value: { name : string, color : string } ) => {
// do sth with *value* that contains *name* and *color*
}
but This looks messy and would recommend going with the way you do not want to and create an interface and then extend the other 2 interfaces from it.
or if you dont want to extends the other interfaces you can just use the interface type as the type to pass in and not extend. It will still work as long as the members exist.
interface NameAndColor {
name: string,
color: string,
}
interface AppleReport {
name: string,
color: string,
age: string
}
interface BananaReport {
name: string,
color: string,
amount: number,
}
const doSth = (value: NameAndColor) => {
// do sth with *value* that contains *name* and *color*
}
let obj = { name : "myName", color : "myColor"};
doSth( obj );
But really the best way is to have your interfaces extend in my opinion.