Here is a code snippet I am currently working on:
const mixed = {
validations: [] as any[],
formattings: [] as any[],
exceptions: [] as any[],
required(message?: string) {
this.validations.push({
name: 'required',
message: message || config.messages.mixed.required,
test: (value: string) => {
return value && value.trim() ? true : false
},
})
return this
},
// other methods that will be reusable
}
const string = () => ({
...mixed,
maxWords(maxWords: number, message?: string) {
type Params = { maxWords: number }
this.validations.push({
name: 'maxWords',
params: { maxWords },
message: message || config.messages.string.maxWords,
test: (value: string, { maxWords }: Params) => {
const wordCount = value.trim().split(' ').length
return wordCount <= maxWords
},
})
return this
},
trim() {
this.formattings.push({
name: 'trim',
format: (value: string) => {
return value.trim()
},
})
return this
},
})
const number = () => ({
...mixed,
positive(message?: string) {
this.validations.push({
name: 'positive',
message: message || config.messages.string.maxWords,
test: (value: string) => {
// make a validation
},
})
return this
},
})
const schema = {
string() {
return string()
},
number() {
return number()
},
// file, date, etc..
}
const form = {
name: schema.string().required().trim().maxWords(3),
age: schema.number().required().positive(),
}
Despite the successful execution of the code, I am facing an issue with IntelliSense not working on all methods in my form validation library.
Here is the problem I am encountering.
Here is a link to the TS Playground where you can test the code in real-time.
The issue lies in the typing of the returned values of each function.