I am currently working on developing a function that will return an array type with custom methods, allowing me to utilize it across various sections of the application.
Typically, this is achieved using Abstract Classes where abstract methods are defined and each class extending it must implement these methods in its unique way. However, I am curious if TypeScript interfaces can be used to achieve a similar outcome.
The following code snippet outlines what I aim to accomplish:
1: Retrieving data from an API endpoint, knowing that it will always return an array of objects. Depending on the specific API method called, the objects may have varying attributes.
2: Understanding the structure of the API response, for instance, calling /posts will result in an array with objects containing a 'name' property. In contrast, calling /posts2 requires a 'specialname' property to be returned when invoking Posts[i].myCustomGetter().
3: The goal is to use the 'Posts' interface in different parts of the application, consistently accessing myCustomGetter without being concerned about the implementation details.
import axios from 'axios'
interface Posts {
[index: number]: Post
}
interface Post {
// Expected properties from Axios Response Data
// Additional custom functions based on usage
myCustomGetter: () => string
}
export async function getPosts(): Promise<Posts> {
return new Promise<Posts>((resolve, reject) => {
axios
.get<Posts>('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
// Defining the myCustomGetter function declaration here
// For example, setting myCustomGetter() => { return thisPost.name }
// Utilizing API knowledge to determine existing properties
resolve(response.data)
})
.catch((error) => {
reject(error)
})
})
}
Your assistance in clarifying this matter would be greatly appreciated.