1

I just started learning typescript. Im just wondering if I can copy one interface data to another but only get specific data.

interface user {
 first_name: string;
 last_name: string;
}

interface user_detail {
 email: string;
 username: string;
 first_name: string;
 last_name: string;
}

const data : user_detail ={
 email: "test@gmail.com";
 username: "test";
 first_name: "test";
 last_name: "test";
}

const _data : user = data;
console.log('_data ->', _data);

what I want is the _data to contain only what is in for user which is only first_name and last_name

big thanks in advance

ampedo
  • 257
  • 2
  • 17

2 Answers2

3

TypeScript is only a tool for annotating your code with type information. It can help you catch errors before your code runs and enhance your IDE, but one of the fundamental philosophies behind TypeScript is that it only makes minimal changes to your code when it's compiled from TypeScript to JavaScript. Most of the time, the only changes that get made during compilation is the removal of TypeScript's type annotations.

To do what you've asked, you would need to write your own function that takes an object of type user_detail and returns an object of type user and then pass your data variable through that function in order to remove the properties you don't want. Just like regular JavaScript, but with type information annotated on it:

interface user {
 first_name: string;
 last_name: string;
}

interface user_detail {
 email: string;
 username: string;
 first_name: string;
 last_name: string;
}

const data : user_detail ={
 email: "test@gmail.com",
 username: "test",
 first_name: "test",
 last_name: "test",
}

function getUser(userDetail: user_detail): user {
  const user: user = {
    first_name: userDetail.first_name,
    last_name: userDetail.last_name,
  };

  return user;
}

const _data : user = getUser(data);
console.log('_data ->', _data);

TypeScript Playground

Mark Hanna
  • 3,206
  • 1
  • 17
  • 25
0

Building upon Mark Hanna's answer as well as this amazing answer using Object Destructuring:

interface user_detail {
  email: string;
  username: string;
  first_name: string;
  last_name: string;
}

const getUser = ({first_name, last_name}: user_detail) => ({first_name, last_name});

type user = ReturnType<typeof getUser>;

The above approach reduces the amount of repeating field names by first creating a function that copies a subset of fields, and then using its return type to define user.

ReturnType is one of TypeScript's "utility types". If the only thing needed is to define the user type, then the Pick utility type could be of help:

type user = Pick<user_detail, "first_name" | "last_name">;
Ilya Nekhay
  • 101
  • 4