8

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)

2 Answers 2

14

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Great!. Could it be declared as a class inheriting from Array<T> (so it would have push/pop etc) and having props/methods?
@Joan, added that option as well, you can create a derived class and do more, but you loose the ability to instantiate with a literal array []
-1

You could try using the following syntax:

let customers: Array<Customer>=[]

It can be referred from their docs for basic types

1 Comment

That was not the question, he wants to be able to write customers.lastDateRetrieved=new Date(); after. Array<Customer> will still not have the lastDateRetrieved property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.