// try trim string
export default function safeTrim(value: unknown): string | undefined {
if (typeof value === 'string') {
return value.trim();
}
return undefined;
}
// index and items used for array
type Validator<T extends object> = (item: T, index?: number, items?: T[]) => null | { [key in keyof T]: string[] };
export function emptyValidator<T extends object>(keyName: keyof T): Validator<T> {
return (item) => {
if (!safeTrim(item[keyName])) {
// @ts-ignore
const error: { [key in keyof T]: string[]} = { // line 18
[keyName]: [`Field should not be empty`],
};
return error;
}
return null;
};
}
// ======= examples usage ========
const testObject = {
propThatReturnNull: 'some string',
propThatReturnError1: '',
propThatReturnError2: undefined,
propThatReturnError3: null
} as const;
emptyValidator('propThatReturnNull')(testObject); // should return null
emptyValidator('propThatReturnError1')(testObject); // should return {propThatReturnError1: [`Field should not be empty`]}
emptyValidator('propThatReturnError2')(testObject); // should return {propThatReturnError2: [`Field should not be empty`]}
emptyValidator('propThatReturnError3')(testObject); // should return {propThatReturnError3: [`Field should not be empty`]}
On line 18 i get error Type '{ [x: string]: string[]; }' is not assignable to type '{ [key in keyof T]: string[]; }'.
I expected that keyName type is "keyof T" instead of "string".
How do I mast link object key and returned object key type?