I need help creating a custom type guard to determine if an array contains nullable or optional elements. I have defined a helper type called RequiredArray
:
type RequiredArray<A extends readonly any[]> =
A extends [infer P, ...infer R]
? [NonNullable<P>, ...RequiredArray<R>]
: []
Although this seems to be working fine, I am encountering issues when trying to write a typeguard for it...
function arrIsFullyDefined<Arr extends readonly any[]>(arr: Arr): arr is RequiredArray<Arr> {
return arr.every((e) => e !== null && e !== undefined);
}
Typescript is giving me an error about potential instantiation of a different type:
A type predicate's type must be assignable to its parameter's type.
Type 'RequiredArray<Arr>' is not assignable to type 'Arr'.
'RequiredArray<Arr>' is assignable to the constraint of type 'Arr', but 'Arr' could be instantiated with a different subtype of constraint 'any[]'.
Type '[] | [unknown]' is not assignable to type 'Arr'.
'[] | [unknown]' is assignable to the constraint of type 'Arr', but 'Arr' could be instantiated with a different subtype of constraint 'any[]'.
Type '[]' is not assignable to type 'Arr'.
'[]' is assignable to the constraint of type 'Arr', but 'Arr' could be instantiated with a different subtype of constraint 'any[]'.
Type '[]' is not assignable to type 'Arr'.
'[]' is assignable to the constraint of type 'Arr', but 'Arr' could be instantiated with a different subtype of constraint 'any[]'.ts(2677)
Initially, I thought this was due to a potentially infinite array type being assigned to the generic Arr
, but even after checking in the RequiredArray
type (using IsFinite
from typescript-tuple), I faced the same issue.
My queries are:
- Why is this causing an error?
- How can I create a typeguard for this helper function?