简体   繁体   English

在typescript中绑定接口构造函数有什么简写吗?

[英]Is there any shorthand for binding interface constructor in typescript?

I'm new in typescript world and I know it is possible to bind arguments of constructor to the class like this 我是打字稿世界的新手,我知道可以将构造函数的参数绑定到类这样的类

class user {
     constructor(private username:string){}
}

instead of 代替

class user {
     constructor(username:string){
           this.username = username;
      }
 }

I just wonder is it possible to do similar thing with interfaces? 我只是想知道是否可以用接口做类似的事情? for example: 例如:

interface IUser{
    username:string;
}

class User implements IUser  {
    constructor( private data:IUser ){
    }
}

There's no shorthand. 没有简写。 You will need to map the properties from the object being passed in to the instance of the class. 您需要将传入的对象的属性映射到类的实例。 You can do that in a number of ways . 你可以通过多种方式实现这一目标 Here's an example: 这是一个例子:

class User implements IUser  {
    username: string;

    constructor(data: IUser) {
        Object.keys(data).forEach((key) => {
            this[key] = data[key];
        });
    }
}

Just be aware that in this example if the passed in object has additional properties then that will map those to your object as well. 请注意,在此示例中,如果传入的对象具有其他属性,那么它也会将这些属性映射到您的对象。

By the way, a the shorter method is to use Object.assign . 顺便说一下,较短的方法是使用Object.assign assign is a new ES6 function on Object . assignObject上的新ES6函数。 You could use the polyfill found on the linked to site to make it work in runtime environments that don't support it. 您可以使用链接到站点上找到的polyfill使其在不支持它的运行时环境中工作。

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

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