使用此功能:
export const combineValidators = <Input extends { [P in keyof Input]: (val: string) => Err }, Err>(
validators: Input
) => (values: { [P in keyof Input]?: unknown }): { [P in keyof Input]: Err } => {
// Ignore implementation.
return {} as { [P in keyof Input]: Err };
};
这种用法:
const validator = combineValidators({
name: (val) => val ? undefined : 'error',
email: (val) => val ? undefined : 'error'
});
const errors = validator({
name: 'Lewis',
email: 'lewis@mercedes.com'
});
我希望TypeScript能够将返回类型推断为:
// Expected: `errors` to be inferred as:
interface Ret {
name: string | undefined;
email: string | undefined;
}
但是可以推断为:
// Actual: `errors` inferred as:
interface Ret {
name: {};
email: {};
}
我创建了一个live example in the TypeScript playground来演示此问题。
有人可以帮忙吗?
答案 0 :(得分:1)
Err
不会以您期望的方式进行推断。使用ReturnType
条件类型从Input
中提取返回类型可能更简单:
type ReturnTypes<T extends Record<keyof T, (...a: any[]) => any>> = {
[P in keyof T]: ReturnType<T[P]>
}
export const combineValidators = <Input extends Record<keyof Input, (val: unknown) => any>>(
validators: Input
) => (values: Record<keyof Input, unknown>): ReturnTypes<Input> => {
return {} as ReturnTypes<Input>;
};
const validator = combineValidators({
name: (val) => val ? undefined : 'error',
email: (val) => val ? undefined : 'error'
});
const errors = validator({
name: 'Lewis',
email: 'lewis@mercedes.com'
});
我们甚至可以走得更远,如果您在验证函数中指定参数类型,则可以对传递给validator
的对象的字段进行类型检查:
type ParamTypes<T extends Record<keyof T, (a: any) => any>> = {
[P in keyof T]: Parameters<T[P]>[0]
}
type ReturnTypes<T extends Record<keyof T, (...a: any[]) => any>> = {
[P in keyof T]: ReturnType<T[P]>
}
export const combineValidators = <Input extends Record<keyof Input, (val: unknown) => any>>(
validators: Input
) => (values: ParamTypes<Input>): ReturnTypes<Input> => {
return {} as ReturnTypes<Input>;
};
const validator = combineValidators({
name: (val: string) => val ? undefined : 'error',
email: (val) => val ? undefined : 'error', // if we leave it out, we still get unknown
age: (val: number) => val ? undefined : 'error'
});
const errors = validator({
name: 'Lewis',
email: 'lewis@mercedes.com',
age: 0
});
const errors2 = validator({
name: 'Lewis',
email: 'lewis@mercedes.com',
age: "0" // type error
});