interface SearchFunc {
(source: string, subString: string): boolean;
}
I often declare a function like this
type Search = (source:string,subString:string)=>void
Why typescript can use interface to declare functions? what is this purpose?
thanks very much
2
Answers
In TypeScript, both interface and type can be used to describe complex types, including function types. However, they have some differences and use cases that may make one more suitable than the other in certain scenarios.
Interfaces in TypeScript define a contract that an object must adhere to. They are great for describing the shape of objects, and they can also describe function types. When you define a function using an interface, you’re essentially defining a function signature that any function (that claims to implement this interface) must adhere to. This is useful, for instance, when you want to ensure that a function passed as a callback or a function stored in an object adheres to a specific.
In summary, whether to use an interface or a type alias to declare a function type in TypeScript depends on your specific needs. If you want to take advantage of features like class implementation and declaration merging, you might want to use an interface. But if you need more flexibility in representing various kinds of types, a type alias might be a better choice.
Using an interface, it ensures that the objects or functions you work with provide better type checking when it’s annotated. In your case, the interface can be implemented this way:
The interface can be annotated this way:
For your reference:
Typescript Function Interface