繁体   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'
});

我的问题是:如何在配置 object 文字中传递指定的类型,以便可以专门化泛型类型 T?

我不知道您的确切用例是什么,但您可以将类型添加到您的界面,如下所示:

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,
});

factory设为通用 function,我们可以将factory的“T”传递给Config ,这也是通用 object。

Config接口开始,使其成为通用接口。

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

接下来, factory function:

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

我们将类型“T”从factory传递给Config

最后,举个例子:

b.ts

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

工厂使用

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