有没有一种方法可以用typescript接口复制抽象类方法



我正在尝试创建一个函数,该函数返回一个具有一些自定义方法的数组类型,并且可以在应用程序的不同部分中使用。

我认为这里的想法通常是用抽象类实现的,在抽象类中,我用几个抽象方法定义了一个抽象类,并且每个扩展该类的类都需要(以自己的方式(实现这些方法。

我想知道是否可以使用TypeScript接口实现类似的功能。

下面的代码大致代表了我想要实现的目标:

1:从API端点获取一些数据,我知道它总是一个对象数组,根据我调用的API方法,这些对象将具有不同的方面。

2:因为在调用api时我知道它的方面,例如,我知道/posts会返回一个数组,数组中的每个对象都有一个名为name的属性,所以每当我调用posts[I].myCustomGetter((时,它实际上都会返回name属性。然而,我知道在调用/posts2时,我实际上想要的是Posts[I].myCustomGetter((来返回specialname属性。

3:我希望能够在我的应用程序的不同部分使用帖子。总是调用myCustomGetter,而不必担心它是如何实现的。

import axios from 'axios'
interface Posts {
[index: number]: Post
}
interface Post {
// I know post will have a couple of properties
// that will come from the Axios Response Data.
// However, I want to add additional custom function
// depending on where I use this interface
myCustomGetter: () => string
}
export async function getPosts(): Promise<Posts> {
return new Promise<Posts>((resolve, reject) => {
axios
.get<Posts>('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
// is there a way to define here the
// function declaration of myCustomGetter() ?
// for example, for this api call, i want 
// myCustomGetter to be something like
// myCustomGetter() => { return thisPost.name }
// and name is something that I know (because I know the api) that will exist
resolve(response.data)
})
.catch((error) => {
reject(error)
})
})
}

如果我听起来很困惑,我很抱歉,但如果有任何帮助,我将不胜感激。

我提出了一个使用接口和类的组合的解决方案。

import axios from 'axios'
interface IPosts {
items: any[]
get(index: number): Post
}
interface Post {
name: string
}
export class Posts implements IPosts {
items: any[]
constructor(items: any[]) {
this.items = items
}
get(index: number): Post {
const item = this.items[index]
return {
// I know that these type of post items have a prop named title.
name: item.title,
}
}
}
export async function getPosts(): Promise<Posts> {
return new Promise<Posts>((resolve, reject) => {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
resolve(new Posts(response.data))
})
.catch((error) => {
reject(error)
})
})
}

现在,每次我想访问其中一个帖子,例如位置0,我都会做一些类似的事情:

getPosts()
.then((Posts: Posts) => {
console.log(Posts.get(0))
})
.catch((error) => {
console.log(error)
})

而且,如果我想确保我的一个函数期望有一个实现IPost的类,我会使用typescript中的通用约束:

function DoSomething<T extends Posts>(arg: T): void {
console.log(arg.get(0))
}
getPosts()
.then((Posts: Posts) => {
DoSomething(Posts)
})
.catch((error) => {
console.log(error)
})

最新更新