Is it possible to transform the original object while converting between different types in Typescript?

Consider having two distinct interfaces:

interface InterfaceOne {
     myString: string,
     myNum: number
}

interface interfaceTwo extends InterfaceOne {
     myBool: boolean
}

Utilizing the TypeScript code below:

let somedata: interfaceTwo = {
     myString: "hello world",
     myNum: 42,
     myBool: false

Is there a method to transform somedata into an InterfaceOne, while eliminating the myBool property from the object?

Answer №1

Yes, it is possible to achieve what you want, but not in the way you currently have it implemented. The issue lies in hardcoding InterfaceTwo into your code. If you simply remove myBool from the data structure, it will not automatically become InterfaceOne as that is not how Object Oriented Programming works. Instead, you will encounter an error. To make your variable capable of holding values of either A or B, avoid extending and simply use both interfaces.

interface InterfaceOne {
    myString: string,
    myNum: number
}

interface InterfaceTwo {
    myBool: boolean
}


let someData: InterfaceOne | InterfaceTwo = {
    myString: "hello world",
    myNum: 42
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trying to save the array returned from Object.keys(obj) into a variable in JavaScript but encountering the error message "ReferenceError: array is not defined"

I'm struggling with this code and can't seem to figure out what's wrong. For some reason, the line "arrKeys = Object.keys(source);" is not returning the array as expected. function findMatchingValues(collection, source) { var arr = []; ...

ReactJS error: Unable to access the setState property

As a newcomer to ReactJS, I have been facing some challenges. I recently familiarized myself with the ES6 syntax, and it claims that the following pieces of code are equivalent in meaning. 1. YTSearch({key: API_KEY, term: 'nba'}, function(vide ...

Distinguishing keyboard and mouse events while focusing in React app

I have been working on implementing keyboard navigation focus outline for accessibility. The pseudo class :focus-visible works well on all elements except for input elements like text or textarea. It seems that inputs always have this pseudo class active s ...

Adjust the Material UI card to fill the maximum available height

I'm currently working with Material UI Card components. You can find more information here. My goal is to set a maximum height for these cards, ensuring that the text and images are displayed nicely. How should I approach this? Below is a snippet of ...

What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another templat ...

Retrieving information from a GET request/JSON payload

It's been a while since I last worked with JavaScript and I'm struggling to figure out how to extract data from a JSON object. Currently, I am making a simple GET request to the Giphy API in order to retrieve URLs from the response, but for some ...

Update the text inside a paragraph using jQuery

When attempting to modify two values within a paragraph using jQuery, I encountered an issue where only one value was successfully updated, leaving the other empty. <div class="container"> <p class="lead custom_bg" id="comment"> updateme! ...

Ways to hear a variable using Google Translate

We're utilizing HTML5 and Javascript. Imagine we have a list containing the names of all players from Barcelona (for example, name = 'Lionel Messi'). I want to make the player's name audible. To achieve this, I would use: var narrator ...

issue with for loop in jquery ajax not processing complete response data

I have a total of 9 columns in my table, namely choosen_emails_1, choosen_emails_2, choosen_emails_3, booking_address, booking_number, booking_message, booking_date, request_date & user_email The for loop is programmed to iterate and display all colum ...

Unlocking the Power of mapState in JavaScript Files

How can I access my states from a `.js` file using `mapState` in Vue.js? I attempted to do so with the following code: import { mapState } from 'vuex'; const foo = { ...mapState(['axios']), }; foo.axios.get('...'); Unfo ...

an issue encountered while trying to print a webpage styled with CSS

Users are given the option to print the current page on the website by clicking on a menu element: <li> <a href="#" onClick="window.print()"> <i class="icon-print"></i> Print Page </a> </li> The page contai ...

What could be the reason that the MVC controller action method marked as HttpPost is not being triggered by an external JavaScript file?

Below is the View cshtml code that is relevant: <tbody> @foreach (var job in Model.JobsList) { <tr> <th onclick="OnJobSelected('@job.JobID')">@job.JobTitle</th> <th>@job.Statu ...

Having an issue with jQuery where trying to append a remove button to a list results in the

Looking to create a dynamic list where users can easily add new items by clicking a button. As each item is added, a corresponding remove button should also be displayed. The issue I'm facing is that every time a new item is added, an extra close but ...

A guide on adjusting a function to pause execution until a line is complete

In the code snippet below, there is an angularJS function named myFunc: $scope.myFunc = () => { myModule.getConfig().update(params); myModule.go(); myModule.log('ok'); }; Additionally, there is a go function defi ...

Executing operations on subdocuments in Mongoose without having to fetch the parent

Currently, when I need to delete a subdocument, I follow this process: Post.findById(post_id).exec(function(err, post) { post.comments.remove({'_id': comment_id}); post.save(function(err) { res.end("Success!"); }); }); This method doe ...

Exploring the possibilities of combining Selenium Code and F# with Canopy

Currently, I am facing the challenge of incorporating Selenium code into my F# project while utilizing the canopy wrapper. Canopy relies on Selenium for certain functions. My main struggle lies in converting Selenium code from Java or C# to fit within an ...

Access information from an array in Angularjs and transfer it to an identifier

I am facing an issue with passing values from the view to the controller and storing them in an array. My goal is to then retrieve a value from the array and pass it as the id value in the update method. Here is my current setup: HTML <label class="c ...

Tips for transferring data using the GET method from the client side to the server side via AJAX

I am attempting to send two dates - a start date and an end date, in order to retrieve data between those two dates. However, my current implementation is not working as expected. $(document).ready(function(){ const date_inputs = new FormData(); ...

Issues with Displaying Components Generated from an Array in JSX

I have a task variable which has the structure as follows: [ team_id_1: { task_id_1: { description: ... }, task_id_2: { description: ... } }, team_id_2: { ... } ] When trying ...

Utilizing JavaScript to send emails from HTML without relying on the default Outlook client

Is it possible to send an email using JavaScript without relying on Outlook or the mailto object? I'm looking for a direct method that can submit form data directly to an email address. Does anyone know of a way to achieve this with JavaScript? ...