繁体   English   中英

获取typescript上泛型类型的参数

[英]Get the parameters of a generic type on typescript

所以,我不知道这在 typescript 中是否可行,但这是我想做的:

使用接收泛型的 class 创建 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来做到这一点。 这将使您获得具有属性的任何 object 中所有键的联合。

type Keys = keyof { a: 123, b: 'string', c: true } // 'a' | 'b' | 'c'

要在 class 中添加一个返回泛型参数的所有属性名称的方法,您可以像这样键入:

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")[]

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM