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: "[email protected]";
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
CodePudding user response:
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: "[email protected]",
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);