Within my object, there are certain values that may be null
or undefined
. If they are, I want to trigger an error and ensure Typescript acknowledges their non-null
/undefined
state when present. Initially, I can achieve this by checking each value individually:
if (!params.target || !params.value) {
throw Error('Missing parameters')
}
const connection: { target: string; value: string } = {
target,
value
}
However, as the function has multiple values to validate, I prefer consolidating these checks into a single helper function. Utilizing the asserts
keyword allows me to assert that an individual value is not null
or undefined
:
function checkMissingParams<T>(value: T): asserts value is NonNullable<T> {
if (value === undefined || value === null) {
throw Error(
'Missing parameters'
);
}
}
Subsequently, in the main function, I implement:
checkMissingParams(params.target)
checkMissingParams(params.value)
const connection: { target: string; value: string } = {
target,
value
}
Nevertheless, my ultimate goal is to apply this technique across an array of values like so:
function checkMissingParams<T>(
values: T[]
): asserts values is NonNullable<T[]> {
const everyValueExists = values.every(
value => value !== undefined && value !== null
);
if (!everyValueExists) {
throw Error(
'Missing parameters'
);
}
}
and consequently
checkMissingParams([params.target, params.value])
Yet, attempting this results in an error stating:
Type 'string | null | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
when trying to execute:
const connection: { target: string; value: string } = {
target,
value
}
Can the asserts
keyword be utilize over an array of values in this manner?