网站搜索

使用接口的一部分创建对象。Typescript


我有一个问题,请帮忙。

我们有两个接口:

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

interface IUserEntityMethods {
    GetFullName(): string;
}

我想创建一个对象,该对象将具有类型 IUserEntityMethods,但是在方法 GetFullName 中,通过 this 在 Webstorm(例如)中会启用自动补全,并且能够使用接口 IUserEntity 的属性。

我最终想得到的是:

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

这是可能的吗?还是有其他选择?

答案#1

我不确定你为什么把方法和属性分成两个接口,但基本上你只需要让一个继承另一个,就像这样:

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;
    }
}

答案#2

你可以使用一个实现了这两个接口的类:

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