简体   繁体   English

如何在 object 文字中专门化泛型类型?

[英]How to specialize a generic type in object literal?

// a.ts
interface Config {
    selector?: <T>(httpResponse: HttpResponse<T>) => unknown;
}

export function factory(options: Config): something {
    // use options to return something
}

// another file b.ts
// I have a type for res only here(b.ts), and I want to use it to specialize type T

import { factory } from 'a.ts';

factory({
    selector: res => res.data.data; // error: Property 'data' does not exist on type 'T'
});

My question is: How to pass a specified type in the config object literal, so that generic type T can be specialized?我的问题是:如何在配置 object 文字中传递指定的类型,以便可以专门化泛型类型 T?

I don't know what your exact use case is but you can add the type to your interface like this:我不知道您的确切用例是什么,但您可以将类型添加到您的界面,如下所示:

interface Config<T> {
  selector?: (httpResponse: T) => unknown;
}

function factory(options: Config<{ data: { data: string } }>) {
  // use options to return something
  return options;
}

factory({
  selector: (res) => res.data.data,
});

Make factory to generic function, and we can pass "T" of factory to Config what also is a generic object.factory设为通用 function,我们可以将factory的“T”传递给Config ,这也是通用 object。

Start from Config interface, make it become generic interface.Config接口开始,使其成为通用接口。

interface Config<T> { // Generically for whole interface
    selector?: (httpResponse: HttpResponse<T>) => unknown;
}

The next, factory function:接下来, factory function:

export function factory<T>(options: Config<T>): something { // return type is "T" or something ?
    // use options to return something
}

We pass type "T" from factory to Config .我们将类型“T”从factory传递给Config

Finally, an example:最后,举个例子:

b.ts b.ts

export type ApiResponse = {
    data: {
        username: string;
    }
}

Usage of factory工厂使用

factory<ApiResponse>({
    selector: res => res.data.data.username, // typehint for the `res`, I try with HttpResponse is AxiosResponse
});

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

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