I am new to Typescript. I couldn't understand the following use of interface:
Say, there is a function :
function test(arg1: ITest):number {
return 20;
}
If the ITest interface is like below :
interface ITest {
(props: string):number;
a1?: number;
}
Then, the below call is valid :
const obj = {
func: (p: string): number => (10+2),
};
test(obj.func); //Should not I pass obj instead of obj.func ?
Q: Should not I pass obj instead of obj.func?
But, if the interface is like below :
interface ITest {
(props: string):number;
a1: number; //Removed the optional sign "?"
}
Q: Then what argument should I pass to the test function ?
Q: what is difference between above interface and the following changed declaration of the interface?
interface ITest {
func: (props: string)=>number; //changed it from (props: string):number;
a1: number;
}
Thank you for clearing out my doubts.
Q: Should not I pass obj instead of obj.func ?
ITest is a function type. It describes a function itself, not an object with a function property or method.
Q: Then what argument should I pass to the test function ?
Now you have declared ITest as a function type with required property a1. The property declaration on a function works in TS by using a function declaration or const expression. Example:
const func = (p: string): number => 10 + 2 // or function declaration func(p: string) {...}
func.a1 = 42
const obj = { func };
test(obj.func) // works now
Q: what is difference between above interface and the following changed declaration of the interface ?
ITest now has become an interface declaration for an object with func and a1 properties.
const o1: ITest = {
func: s => 137,
a1: 42
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With