If you want your sample code to function correctly, you must have declarations that correspond to each line within the code snippet. Let's delve into them:
const cArray = new CustomArray<number>(1,3,2,3);
For this code block to execute properly, you need a value called CustomArray
, with its type being a constructor ("newable") signature that accepts a variable list of T
values and returns a CustomArray<T>
value. This should not be added to the CustomArray<T>
interface but should instead be declared as follows:
declare const CustomArray: new <T>(...a: T[]) => CustomArray<T>;
cArray[0] = 2;
console.log(cArray[2]) // 2
In order for these lines to work, the CustomArray<T>
interface needs to include a numeric index signature where the values are of type T
, like this:
[n: number]: T;
for (const i of cArray) {
console.log(i);
}
For this part to operate successfully, the CustomArray<T>
interface should be made to be iterable, meaning it has a method titled Symbol.iterator
that returns an Iterator<T>
:
[Symbol.iterator](): IterableIterator<T>;
The same modifications need to be applied for your CustomMap
to function as intended. Here is how I would expect your declarations to be structured:
//iter.d.ts
interface CustomMap<U, V> {
get(key: U): V | undefined;
set(key: U, val: V): void;
[Symbol.iterator](): IterableIterator<[U, V]>
}
declare const CustomMap: new <U, V>(...a: [U, V][]) => CustomMap<U, V>;
interface CustomArray<T> {
length(): number;
[n: number]: T;
[Symbol.iterator](): IterableIterator<T>;
}
declare const CustomArray: new <T>(...a: T[]) => CustomArray<T>;
With these in place, the following snippets should compile without errors (ensure proper declaration for variables like cArray
and cMap
):
//test.ts
const cArray = new CustomArray<number>(1, 3, 2, 3);
cArray[0] = 2;
console.log(cArray[2]) // 2
for (const i of cArray) {
console.log(i);
}
const cMap = new CustomMap<string, string>(['1', 'a'], ['3', 'b'], ['2', 'ç'], ['4', 'd']);
for (const [k, v] of cMap) {
console.log(k + ':' + v);
}
I hope this clarifies things for you and wish you good luck!
Link to modified code