简体   繁体   English

用值填充接口属性

[英]Populate an interface property with values

I have an interface which I want to be populated automatically with some default data when I assign variables to it. 我有一个接口,当我给它分配变量时,我想用一些默认数据自动填充它。 The interface is saved in a module and I want to use it on other modules. 该接口保存在一个模块中,我想在其他模块上使用它。 How do I assign data to interface properties ? 如何为接口属性分配数据?

 export interface NameAge { valueList : Array<{ 'Name', 'Age' }>; } 

So I create let's say some variables in multiple modules that implement this interface. 因此,我假设在实现此接口的多个模块中创建了一些变量。
How do I assign some default value to the NameAge property. 如何为NameAge属性分配一些默认值。 I can do it with a class containing listUsers as public static property but can't replace interface with class. 我可以使用包含listUsers作为公共静态属性的类来做到这一点,但不能用类替换interface。 Also I want the interface and the listUsers array of objects to be in the same module so I when I import the module, I get both the interface and listUsers with the default data already populated. 另外,我希望接口和对象的listUsers数组位于同一模块中,因此在导入模块时,我同时获得了接口和listUsers以及已填充的默认数据。 Thanks :)) 谢谢 :))

Interfaces will not allow you to do that. 接口将不允许您这样做。

However you can do it with classes. 但是,您可以使用类来实现。

class NameAge {
    public valueList: Array<{ 'Name', 'Age' }> = [{
        'Name': 'J',
        'Age': 'ABC'
    }];
}


class NameAgeChild extends NameAge {
    public child: boolean

    public adults() {
        return this.valueList.filter(v => v.Age >= 18);
    }
}

This however makes sense only if you need a class for this value (code + behaviour together) in your app. 但是,仅当您需要在应用中为此值(代码+行为一起)使用一个类时,这才有意义。

If not, just make a constant with the your values and use it when you create new instances. 如果不是,则使用您的值创建一个常数,并在创建新实例时使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM