Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript: array with properties / array as a class

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)

like image 538
tru7 Avatar asked Mar 07 '23 20:03

tru7


1 Answers

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();
like image 68
Titian Cernicova-Dragomir Avatar answered Mar 17 '23 05:03

Titian Cernicova-Dragomir