I have this javascript code
class Customer{
...
}
let customers:Customer[]=[];
customers.lastDateRetrieved=new Date;
Somehow customers is both a class (it has properties) and an array. How would you declare this construction in typescript? I can not find a way to derive from array (if that makes sense)
You can use an intersection type:
let customers:Customer[] & { lastDateRetrieved?: Date} =[];
customers.lastDateRetrieved=new Date ();
Or you can create a general type for this use case:
type ArrayWithProps<T> = T[] & { lastDateRetrieved?: Date}
let customers:ArrayWithProps<Customer> =[];
customers.lastDateRetrieved=new Date ();
You could also create a class derived from array, but then you would need to use the constructor of the class to initialize the array, and you can't use []
:
class ArrayWithProps<T> extends Array<T> {
lastDateRetrieved: Date;
constructor (... items : T[]){
super(...items);
}
}
var f = new ArrayWithProps();
f.push(new Customer());
f.lastDateRetrieved = new Date();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With