Will Luce Will Luce - 1 month ago 19
TypeScript Question

Setting properties from one interface in another with inheritance

Is it possible to set the properties of one interface by generating an instance of another from which the first interface inherits?

For example, I have a

user
interface with a function that generates a random instance.

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


Then I have another interface for a more specific user, let's say it's
ProUser
, which has another generate function

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


Is there an easy way to map these properties over? I have other user types that could use this mapping functionality as well.

Answer

You can simply do:

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

    return randomProUser;
}

Another option is to use Object.assign:

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

    randomProUser.favoriteColor = Chance.color();

    return randomProUser;
}
Comments