For extracting a type mapping from an object with native type validation functions, consider the following scenario:
const test = {
Test: {
Test1: {
Test2: SimpleStringValidator //return type is string or undefined but input can be anything
},
}
}
The desired extracted type should look like this:
type Extracted = {
Test: {
Test1: {
Test2: string
}
}
}
This code snippet aims to extract the return types of an object containing nested validation functions:
Sample.ts
// Types for validators
export type Validator<T> = NativeTypeValidator<T> | ObjectValidator<T>
export type NativeTypeValidator<T> = (n: any) => T | undefined
export type ObjectValidator<O> = {
[K in keyof O]: Validator<O[K]>
}
// Sample native validator function
export const SimpleStringValidator:NativeTypeValidator<string> = (val) => typeof(val) === "string" ? val : undefined
// Function for object validation
export const ObjValidator = <V>(validatorObj: ObjectValidator<V>) => (o:any):V =>{
let result = {} as V;
if (typeof (o) !== "object") { return undefined; }
const validatorKeys = Object.keys(o) as [keyof ObjectValidator<V>]
validatorKeys.forEach((validatorKey) => {
const objValue = o[validatorKey] as V[keyof V];
const objectValidator = validatorObj[validatorKey]
if (!objectValidator) { return undefined }
if (typeof (objectValidator) === "object") {
result[validatorKey] = ObjValidator(objectValidator as ObjectValidator<V[keyof V]>)(objValue)
}
else {
const nativeValidator = objectValidator as NativeTypeValidator<V[keyof V]>;
result[validatorKey] = nativeValidator(objValue)
}
})
return result;
}
// Initial test object
export const test = {
Test: {
Test1: {
Test2: SimpleStringValidator
},
}
}
// Generating output based on validation
export const validatorFunc = ObjValidator(test);
export const outputExample = validatorFunc({
Test: {
Test1: {
Test2: "hi"
},
}
})
outputExample.Test.Test1.Test2 = "1";
outputExample.Test.Test1.Test2 = 1;
In some cases, there might be a discrepancy between autocomplete suggestions and generated declaration files. The issue arises when exporting the generated type information to other projects.
Generated sample.d.ts
export declare type Validator<T> = NativeTypeValidator<T> | ObjectValidator<T>;
// Other declarations...
export declare const outputExample: {
Test: {
Test1: any;
};
};
To resolve this type discrepancy during export, ensure that the root validator object is used as the source for the extracted type. This will generate correct type information in the declaration file for seamless integration with other projects.
Explore this Typescript Playground example for further insights.