所以,我不知道这在 typescript 中是否可行,但这是我想做的:
使用接收泛型的类来创建 GraphQL 查询
class BackendClient<T> {
type: string
endpoint: string
query: Object
constructor(type: string, endpoint: string, query: Object) {
this.type = type
this.endpoint = endpoint
this.query = query
}
async doQuery(): Promise<T> {
var data: string
data = `${this.type} { ${this.endpoint}(`
Object.getOwnPropertyNames(this.query).forEach(element => {
data += `${element}: ${this.query[element]},`
})
data += `) {`
T.parameters.forEach(element => {
data += `${element},`
})
data += `} }`
return await axios({
url: constants.ApiUrl,
method: 'post',
data: {
query: data
}
}) as T
}
}
例如,我有一个执行此操作的代码
interface Search {
title: string
}
interface Response {
id: number
title: string
image_url: string
}
async function main() {
var search: Search = { title: "a" }
var client = new BackendClient<Response>('query', 'search', search)
console.log(await client.doQuery())
}
main()
如何获取 BackendClient 上的响应参数?
最佳答案
参数在这种情况下是一个非常模糊的词,它在某种程度上取决于您的目标是什么,但听起来您想知道通用参数具有哪些属性名称,然后在其他类型中使用它?
如果是这样,您可以使用keyof
来做到这一点。这将使您获得任何具有属性的对象中所有键的并集。
type Keys = keyof { a: 123, b: 'string', c: true } // 'a' | 'b' | 'c'
要在类中添加一个返回泛型参数的所有属性名称的方法,您可以像这样键入:
class BackendClient<T> {
getGenericProperties(): (keyof T)[] {
// skipping implementation
return 'any' as any
}
}
interface ResponseData {
id: number
title: string
image_url: string
}
const client = new BackendClient<ResponseData>()
const properties = client.getGenericProperties()
// inferred type: ("id" | "title" | "image_url")[]
关于javascript - 获取 typescript 上泛型类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61397074/