使用继承

时间:2016-10-11 17:44:00

标签: inheritance typescript interface

是否可以通过生成第一个接口继承的另一个接口的实例来设置一个接口的属性?

例如,我有一个user接口,其中包含一个生成随机实例的函数。

import * as Chance from 'chance';

export interface User {
    username: string;
    firstName: string;
    lastName: string;
    password: string;
    email: string;
    gender: string;
    streetAddress: string;
    city: string;
    state: string;
    zipCode: string;
    country: string;
    phoneNumber: string;
}

export function generateRandomUser(): User {
    let randomuser: User;

    randomuser.firstName = Chance.first();
    randomuser.lastName = Chance.last();
    randomuser.username = randomuser.firstName + randomuser.lastName;
    randomuser.password = 'password';

    return randomuser;
}

然后我有一个更具体的用户的另一个界面,让我们说它是ProUser,它有另一个生成函数

import { User, generateRandomUser } from '../user';
import * as Chance from 'chance';

interface ProUser extends User {
    favoriteColor: string;
}

function generateRandomProUser(): ProUser {
    let generalUser = generateRandomUser();
    let randomProUser: ProUser;

    // simple way to set the props from generalUser to randomProUser??

    randomProUser.favoriteColor = Chance.color();

    return randomProUser;
}

有没有简单的方法来映射这些属性?我还有其他用户类型也可以使用这种映射功能。

1 个答案:

答案 0 :(得分:1)

您可以这样做:

function generateRandomProUser(): ProUser {
    let randomProUser = generateRandomUser() as ProUser;
    randomProUser.favoriteColor = Chance.color();

    return randomProUser;
}

另一种选择是使用Object.assign

function generateRandomProUser(): ProUser {
    let generalUser = generateRandomUser();
    let randomProUser = Object.assign({}, generalUser) as ProUser;

    randomProUser.favoriteColor = Chance.color();

    return randomProUser;
}