我正在尝试创建一个类型安全的map函数(不是下面的函数),但我坚持要获得函数参数才能正确推断。
export type Mapper<U extends Unmapped> = {
mapped: Mapped<U>
};
export type Unmapped = {
[name: string]: (...args: any[]) => any
};
export type Mapped<U extends Unmapped> = {
[N in keyof U]: (...args: any[]) => Promise<any>
};
const map = <U extends Unmapped>(unmapped: U): Mapper<U> => ({
mapped: Object.entries(unmapped).reduce(
(previous, [key, value]) => ({
...previous,
[key]: (...args: any[]) => new Promise((resolve) => resolve(value(...args)))
}),
{}
) as Mapped<U>
});
const mapped = map({ test: (test: number) => test });
mapped.mapped.test('oh no');
有没有可能让TypeScript来推断它们?目前,mapped
对象内部的函数接受任何参数,但它应该只接受未映射对象中定义的参数。函数名可以正确推断出来。
发布于 2018-06-09 21:33:06
如果您使用(...args: any[]) => Promise<any>
作为映射类型中的签名,您将丢失所有参数类型信息并返回类型信息。使用条件类型可以实现您想要做的事情的不完美的解决方案。here描述了这些限制。
该解决方案将需要创建一个条件类型,该类型使用给定数量的参数分别处理每个函数。下面的解决方案适用于最多10个参数(对于大多数实际情况来说已经足够了)
export type Mapper<U extends Unmapped> = {
mapped: Mapped<U>
};
export type Unmapped = {
[name: string]: (...args: any[]) => any
};
type IsValidArg<T> = T extends object ? keyof T extends never ? false : true : true;
type Promisified<T extends Function> =
T extends (...args: any[]) => Promise<any> ? T : (
T extends (a: infer A, b: infer B, c: infer C, d: infer D, e: infer E, f: infer F, g: infer G, h: infer H, i: infer I, j: infer J) => infer R ? (
IsValidArg<J> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J) => Promise<R> :
IsValidArg<I> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I) => Promise<R> :
IsValidArg<H> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H) => Promise<R> :
IsValidArg<G> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => Promise<R> :
IsValidArg<F> extends true ? (a: A, b: B, c: C, d: D, e: E, f: F) => Promise<R> :
IsValidArg<E> extends true ? (a: A, b: B, c: C, d: D, e: E) => Promise<R> :
IsValidArg<D> extends true ? (a: A, b: B, c: C, d: D) => Promise<R> :
IsValidArg<C> extends true ? (a: A, b: B, c: C) => Promise<R> :
IsValidArg<B> extends true ? (a: A, b: B) => Promise<R> :
IsValidArg<A> extends true ? (a: A) => Promise<R> :
() => Promise<R>
) : never
);
export type Mapped<U extends Unmapped> = {
[N in keyof U]: Promisified<U[N]>
}
const map = <U extends Unmapped>(unmapped: U): Mapper<U> => ({
mapped: Object.entries(unmapped).reduce(
(previous, [key, value]) => ({
...previous,
[key]: (...args: any[]) => new Promise((resolve) => resolve(value(...args)))
}),
{}
) as Mapped<U>
});
const mapped = map({ test: (test: number) => test });
mapped.mapped.test('oh no');
发布于 2019-03-08 09:55:53
可以使用Parameters
和ReturnType
泛型来获取函数的具体参数和返回类型:
type Promisified<T extends (...args: any[]) => any> = (...args: Parameters<T>) => Promise<ReturnType<T>>;
export type Mapped<U extends Unmapped> = {
[N in keyof U]: Promisified<U[N]>
}
https://stackoverflow.com/questions/50773038
复制相似问题