我在这个操场上有以下代码:
export enum HTTPMethod {
GET = 'GET',
}
export type FetchData<TData> = (
routeOrBody?: string | BodyInit | object,
body?: BodyInit | object,
) => Promise<TData | undefined>
export type AbortFetch = () => void;
export interface FetchCommands<TData> {
get: FetchData<TData>
abort: AbortFetch
}
export interface UseFetchResult<TData>{
data: TData,
request: FetchCommands<TData>
}
export type FetchResult<TKey extends keyof FetchCommands<TData>, TData> = {
data: TData
} & {
[key in TKey]: any
}
const makeHttpVerbMethod = <TData, TMethod extends keyof FetchCommands<TData>>(
httpMethod: HTTPMethod,
) => (incoming: TData): FetchResult<TMethod, TData> => {
const methods: FetchCommands<TData> = {
get: () => Promise.resolve(undefined),
abort: () => undefined
}
const {request}: UseFetchResult<TData> = { data: incoming, request: methods }
const commandKey = httpMethod.toLowerCase() as TMethod
const httpFunc = request[commandKey]
const result: FetchResult<TMethod, TData> = {
data: incoming,
[commandKey]: httpFunc,
}
return result
}
基本上,我想为makeHttpVerbMethod函数返回的内容添加一个键,但我不完全确定这是否可能,我正在使用泛型类型参数来尝试限制可以调用的键:
const makeHttpVerbMethod = <TData, TMethod extends keyof FetchCommands<TData>>(
httpMethod: HTTPMethod,
) => (incoming: TData): FetchResult<TMethod, TData> => {
我想为返回类型添加一个动态键makeHttpVerbMethod
但我认为 tsc 感到困惑,因为我在尝试分配给result.
键入'{ [x:字符串]:TData | FetchCommands[TMethod]; 数据:TData;}' 不可分配给类型 'FetchResult'。键入'{ [x:字符串]:TData | FetchCommands[TMethod]; 数据:TData;}' 不可分配给类型 '{ [TMethod 中的键]: any; }'。
我不明白{ [x: string]从哪里来
如果我将函数更改为使用显式'get'文字,那么一切正常
const makeHttpVerbMethod = <TData, TMethod extends keyof FetchCommands<TData>>(
httpMethod: HTTPMethod,
) => (incoming: TData): FetchResult<'get', TData> => {
const methods: FetchCommands<TData> = {
get: () => Promise.resolve(undefined),
abort: () => undefined
}
const {request}: UseFetchResult<TData> = { data: incoming, request: methods }
const commandKey = 'get'
const httpFunc = request[commandKey]
const result: FetchResult<'get', TData> = {
data: incoming,
[commandKey]: httpFunc,
}
return result
}
有没有办法使用参数化类型 TMethod 进行这项工作?