简体   繁体   中英

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?

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.

Start from Config interface, make it become generic interface.

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

The next, 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 .

Finally, an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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