i have a generic interface like this
type myType =
{
value1:string;
value2:string;
}
and a class
class array<myType> extends Array<myType>
{
let a:myType;
a.value1 ==> error.
}
the problem is that inside the class, the type myType is not read correct as it is another thing, how can i solve this?
CodePudding user response:
To have the elements of this array inferred to be MyType
, declare a class with a unique name that extends Array<MyType>
. Individual elements of the array can be referred to using this[index]
.
Here's an example (and a playground link):
type MyType = {
value1: string;
value2: string;
};
class MyTypeArray extends Array<MyType> {
getCombinedValues(index: number) {
// type of elementAtIndex is inferred as MyType
const elementAtIndex = this[index];
return `${elementAtIndex.value1} ${elementAtIndex.value2}`
}
}
const myTypeArray = new MyTypeArray({ value1: 'Hello', value2: 'world' });
// Prints 'Hello world'
console.log(myTypeArray.getCombinedValues(0));