获取打字稿上通用类型的参数

时间:2020-04-23 21:12:30

标签: javascript typescript graph typescript-generics

所以,我不知道这在打字稿中是否可行,但这是我想要做的:

使用接收泛型的类来创建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上获取响应参数?

1 个答案:

答案 0 :(得分:1)

在这种情况下,参数是一个非常模糊的词,它取决于您的目标,但听起来您想知道通用参数具有哪些属性名称,然后在其他类型中使用它?

如果是这样,您可以使用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")[]

Playground