TS 可以在 interface 内使用泛型吗?

比如我有一个接口如下:

export interface CusSelectProps {
    request?: <T>(params?: Record<string, any>) => Promise<DataList<T>>;
    optionShape?: <T>(res: T) => ({ label: any; value: any });
}

定义时没有报错,但是我不清楚改如何实例化,就是实际用的时候会报错,有大佬可以帮忙看下吗

阅读 2k
3 个回答

请注意这里的<T>并不是CusSelectProps的参数(CusSelectProps没有参数), 而是属性函数的类型参数你在实现这个接口的时候, TS会根据request和optionShape的参数和返回值类型来推导T的类型, 这个类型是满足request和optionShape的定义的最佳类型.

举个例子(request你没有给DataList定义, optionShape那个类型参数你没有使用)

const props: CusSelectProps  = {
    request: (arg) => Promise.resolve([]),
    optionShape: (arg) => ({label: '??', value: 123})
}

具体详见:
https://www.typescriptlang.or...

使用是需要传递类型参数,例如:

const req: CusSelectProps.request<string>;
cosnt options: CusSelectProps.optionShape<{name: string}>;
export interface CusSelectProps {
    request?: <T>(params?: Record<string, any>) => Promise<DataList<T>>;
    optionShape?: <T>(res: T) => ({ label: any; value: any });
}

// 方法实现
class Foo implements CusSelectProps {
    request<T>(params?: Record<string, any>) {
        return new Promise(s => {
            // 具体的功能略,当然也没法写,这需要根据你的业务情况
            s(new DataList<T>());
        });
    }
}

// 调用
const foo = new Foo();
const record = {} as Record<string, any>;
record['bar'] = 'foo';
foo.request<string>(record).then((data: DataList<string>) => {
    // 这的 DATA 就是装有string类型的DataList
    console.log(data);
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进