I have deof following codefunction:
const selector = (definitions, query = {}) => {
const select = {};
Object.keys(definitions).forEach((key) => {
if (typeof query[key] !== 'undefined') {
if (definitions[key].validation(query[key])) {
if (typeof definitions[key].convert !== 'undefined') {
select[key] = definitions[key].convert(query[key], key);
} else {
select[key] = query[key];
}
} else if (typeof definitions[key].default !== 'undefined') {
select[key] = definitions[key].default;
}
} else if (typeof definitions[key].default !== 'undefined') {
select[key] = definitions[key].default;
}
});
return select;
};
This typescript is report me that a need to type correcty definitions and query but i really don't know how.
Error Message.
Element implicitly has an 'any' type because type '{}' has no index signature.
How can I do it?
Usage:
const config = {
name: {
validation: val => val.length >= 3
},
page: {
validation: val => Number.isInteger(parseInt(val, 10)),
default: 1,
},
limit: {
default: 10,
}
}
const myQuery = {
name: 'da',
page: 'no-unber',
another: '1',
}
select(config, myQuery)
Test
const expected = JSON.stringify({
page: 1,
limit: 10,
})
const output = JSON.stringify(selector(config, myQuery))
if (expected !== output) {
throw new Error(`The output is wrong.\nExpected: ${expected}\nOutput: ${output}`)
}
Case of usage: https://jsbin.com/gatojir/edit?js,console
Note: validation is required, but convert, and default are optional parameters.