使用部分接口创建对象。打字稿

时间:2016-04-19 22:02:11

标签: typescript

我有问题,请帮忙。

我们有两个接口:

interface IUserEntity {
    Id: number;
    FirstName: string;
    LastName: string;
}

interface IUserEntityMethods {
    GetFullName(): string;
}

我想创建一个类型为IUserEntityMethods的对象,但在Webstorm中的方法GetFullNamethis内(例如)删除了自动完成功能并能够使用属性接口IUserEntity

我最终想要得到什么:

var userEntityMethods: IUserEntityMethods = {
    GetFullName: function() {
        return this.FirstName + " " + this.LastName; // We have no errors at this line.
    }
}

这可能吗?或者还有其他选择吗?

2 个答案:

答案 0 :(得分:0)

我不确定为什么你将这些方法从属性划分为两个接口,但基本上你需要做的就是让一个扩展另一个接口,如下所示:

interface IUserEntity {
    Id: number;
    FirstName: string;
    LastName: string;
}

interface IUserEntityMethods extends IUserEntity {
    GetFullName(): string;
}

然后IUserEntityMethods的实例应具有方法和属性 但是你需要在具体的实例中使用它们:

var userEntityMethods: IUserEntityMethods = {
    Id: A_NUMBER,
    FirstName: A_STRING,
    LastName: A_STRING,
    GetFullName: function() {
        return this.FirstName + " " + this.LastName;
    }
}

答案 1 :(得分:0)

您可以使用实现两个接口的类:

class UserEntity implements IUserEntity, IUserEntityMethods {
    public Id: number;
    public FirstName: string;
    public LastName: string;

    public GetFullName(): string {
        return this.FirstName + " " + this.LastName;
    }
}

然后你可以像这样使用它:

const userEntity: UserEntity = new UserEntity();
userEntity.Id = 1;
userEntity.FirstName = "John";
userEntity.LastName = "Doe";
console.log(userEntity.GetFullName());