javascript - 在打字稿上获取泛型类型的参数
问题描述
所以,我不知道这在打字稿中是否可行,但这是我想做的:
使用接收泛型的类来创建 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")[]
推荐阅读
- tensorflow - Tensorflow tf.data.Dataset API,数据集解压功能?
- reactjs - 导航 UI 卡住时使用 redux-persist 做出反应
- iis - 如果您通过域名访问,则会出现 Windows 身份验证提示
- light-inject - 使用 LightInject,如何在不注册一堆工厂的情况下将参数传递给子依赖项?
- python - Python - 在几个较小的数据帧中切片数据帧
- php - 如何在 Vagrant 和 Homestead 中回滚 PHP 版本?
- html - 文本对齐适用于一个标签但不适用于另一个标签?
- wordpress - 无法同时从本地和外部访问 Wordpress 站点
- r - 如何绘制角度在 0-360 度之间的线
- c# - Convert Char[] to Int,战争纸牌游戏