【问题标题】:typescript: array with properties / array as a class打字稿:具有属性/数组作为类的数组
【发布时间】:2023-03-13 06:13:01
【问题描述】:

我有这个 javascript 代码

class Customer{
    ...
}

let customers:Customer[]=[];
customers.lastDateRetrieved=new Date;

不知何故,客户既是一个类(它具有属性)又是一个数组。 你将如何在打字稿中声明这种结构?我找不到从数组派生的方法(如果有意义的话)

【问题讨论】:

    标签: arrays class typescript


    【解决方案1】:

    你可以使用交集类型:

    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();
    

    【讨论】:

    • 太棒了!是否可以将其声明为继承自 Array 的类(因此它会有推送/弹出等)并具有道具/方法?
    • @Joan,也添加了该选项,您可以创建派生类并做更多事情,但是您失去了使用文字数组实例化 [] 的能力
    【解决方案2】:

    您可以尝试使用以下语法:

    let customers: Array<Customer>=[]
    

    可以参考他们的文档for basic types

    【讨论】:

    • 这不是问题,他希望之后能够写customers.lastDateRetrieved=new Date();Array&lt;Customer&gt; 仍然没有 lastDateRetrieved 属性。
    猜你喜欢
    • 2023-01-14
    • 2016-11-01
    • 2021-12-17
    • 2016-08-03
    • 2019-08-28
    • 2021-02-04
    • 2019-09-25
    • 2018-06-11
    相关资源
    最近更新 更多