Reputation: 7212
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)
Upvotes: 6
Views: 3461
Reputation: 249546
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();
Upvotes: 12
Reputation: 545
You could try using the following syntax:
let customers: Array<Customer>=[]
It can be referred from their docs for basic types
Upvotes: -1