Exploration
Uncomfortable type definition at the library:
declare type Extension = {
extension: Extension;
} | readonly Extension[];
Type-validation function
export function isIterable(x: any): x is Iterable<unknown> {
return Symbol.iterator in x;
}
Solution Implementation
Utilizing the type-validation function
const extensions:Extension = getExtensions();
if (!isIterable(extensions)) { // Validation
throw Error('extensions should be iterable');
}
console.log(...extensions); // Executing successfully
Dilemma
Efforts to devise a Helper function for Type-checking:
import { isIterable } from '../type-guarded/isIterable';
export const throwIfNotIterable = <T,>(value: T) => {
if (isIterable(value)) {
return value;
}
throw TypeError(
`Expected to be iterable, but received ${value} (${typeof value})`
);
};
Note: Inferred type:
const throwIfNotIterable: <T>(value: T, name: string) => T & Iterable<unknown>;
Trial and Error
Attempt 1
console.log(...throwIfNotIterable(extensions));
ERROR:
Type 'unknown' cannot be assigned to type 'Extension'.
Attempt 2
throwIfNotIterable(extensions, 'not iterable');
console.log(...extensions);
ERROR:
Type 'Extension | undefined' should have a '[Symbol.iterator]()' method that provides an iterator.
Seeking insight on my errors?