我有这个javascript代码
class Customer{
...
}
let customers:Customer[]=[];
customers.lastDateRetrieved=new Date;
不知何故,客户既是一个类(它有属性)又是一个数组。 你会如何在 typescript 中声明这个结构?我找不到从数组派生的方法(如果有意义的话)
最佳答案
您可以使用交集类型:
let customers:Customer[] & { lastDateRetrieved?: Date} =[];
customers.lastDateRetrieved=new Date ();
或者您可以为这个用例创建一个通用类型:
type ArrayWithProps<T> = T[] & { lastDateRetrieved?: Date}
let customers:ArrayWithProps<Customer> =[];
customers.lastDateRetrieved=new Date ();
你也可以创建一个从数组派生的类,但是你需要使用类的构造函数来初始化数组,并且你不能使用[]
:
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();
关于arrays - typescript :具有属性/数组作为类的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884724/