How do I turn the array check into a function, and not get an error in the code where the array check used to be?
The original function body is "start", and I intend to turn the function body into "start1". However, when I do that, an error shows up on the line as noted below.
type JSONRPCParams = object | any[]; // this is in another module where I cannot change the source
async function start(params: JSONRPCParams | undefined) {
// the intention is to turn the following check into a function
if (!params || !Array.isArray(params) || params.length === 0) {
throw new Error('invalid parameter(s) provided');
}
const assetConfig = params[0]; // this is ok when the check is inline
}
function validateParams(params: JSONRPCParams | undefined) {
if (!params || !Array.isArray(params) || params.length === 0) {
throw new Error('invalid parameter(s) provided');
}
}
async function start1(params: JSONRPCParams | undefined) {
validateParams(params);
const assetConfig = params[0]; // this is not ok, when the check becomes a function
}
The error is: 'params' is possibly 'undefined'.ts(18048) Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'JSONRPCParams'. Property '0' does not exist on type 'JSONRPCParams'.ts(7053)
I also tried writing validateParams as follows, but it doesn't work, the same error as above is seen.
if (params && Array.isArray(params) && params.length >= 0) {
return;
}
throw new Error('Invalid parameter(s) provided');
How do I write the validateParams function so that in the start1 function, I don't get an error on the commented line?
I've researched other similar Stackoverflow questions, but they do not handle this issue.
Your expertise and help is appreciated.
Thank you.