TypeScript - Creating a custom function that extracts a segment of the given input

As a newcomer to Typescript, I am looking to create a function that can modify an object by filtering out certain information.

Consider the following Type definition:

type movie = {id: number, title:string, url:string, rating:number}

I need a function that takes an array of movies as input and outputs the same array but only with id and title included.

For example, if the input is:

[{id:1, title:Wonder Woman, url: www, rating:5},{id:2, title: Super Man, url:www2, rating:7}]

The desired output should be:

[{id:1, title:Wonder Woman},{id:2, title: Super Man}]

Are there any straightforward methods to achieve this?

Answer №1

To let TS know that you are dealing with only a portion of a type (referred to as a Partial), you can make use of the Partial<...> syntax.

type Movie = { id: string | number, name: string, url: string }

const movies: Movie[] = [
  { id: 1, name: "Movie A", url: "http://www.google.com" },
  { id: 2, name: "Movie B", url: "http://www.google.com" }
]

function stripUrl ({ id, name }: Movie): Partial<Movie> {
  return { id, name }
}

const mMovies = movies.map(stripUrl)

https://i.sstatic.net/81TZ7.png

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

Using Angular and TypeScript to create an implementation of TodoMVC

Currently delving into Typescript and Angular, I recently encountered an issue with an unregistered controller due to its script being loaded after the application module's script. To find a solution, I inspected the index.html file from the TodoMVC s ...

Allow Visual Studio Code to create a constructor for Typescript class

When developing Angular 2 apps in Typescript using Visual Studio Code, one common task is writing constructors with their parameter list. Is there a way to save time and effort on this? It would be really helpful if the IDE could automatically generate th ...

Vue3 does not support parameter assignment

I am working on creating a function that takes two parameters, a string and an array. The array is meant to be filled with data obtained from Axios. However, I am encountering the issue {'assignment' is assigned a value but never used.}. My goal ...

Error: Unable to iterate over the albumlist property as it is not a function

I keep encountering the error message TypeError: this.state.albumlist.map is not a function whenever I attempt to display the retrieved data. I am unable to pinpoint the exact issue in my code that is causing this error. Can anyone assist me with troubles ...

One way to display buttons only for the first row in a mat-table

I am working with a mat-table that displays a list of executing Jobs. Currently, there are stop and re-execute buttons in front of all the rows. However, I now want to only show the button on the first row. How can I achieve this? Here is the code for the ...

How can you populate an observable with another observable and then return the resulting observable?

I am currently working on a project using rxjs and json-server as the database provider. I have encountered an issue while trying to populate one collection with another. The two collections in question are Match and Tournament. The Match collection conta ...

Discover the best practices for implementing services within the import decorator of an angular module configuration

Is there a way to access a service inside the load module in Angular, especially when the module is loaded from a decorator and the service is not yet DI? You can refer to this answer for an example. For instance, if the method in the service returns an ...

How to display the content of a file using C programming

As I delve into learning how to manipulate files in C, I decided to experiment with writing and reading text from a file using the following code: FILE *f = fopen("testingText.txt", "w"); char *text = "This is text1..."; fw ...

The 'isMounted' property is not found in the 'ErrorBoundary' type

I'm currently working on my TypeScript skills and I've come across a bug that's hindering my progress: Property 'isMounted' does not exist on type 'ErrorBoundary'. The following is my Error Boundary component: // Reac ...

The use of defaultProps is no longer supported, yet it is still featured in official documentation

Using my Component in React 18.2 like this: const Component = ({prop=true}) => (<div></div>) Results in an error message in the console stating: Support for defaultProps will be removed from function components in a future major release. ...

The presence of this container with Mongoose Schema Typescript eclipses an external 'this' value

Here's my schema validator code for MongoDB: UserSchema.path('email').validate(async function (email: string) { const count = await User.count({ email, _id: { $ne: this._id } }) return !count }, 'Email already exists') However ...

What causes the disappearance of my matrix values in C programming?

I have been working on a 2D sand simulation using basic cellular automata concepts and aiming to display it in the console. However, I've encountered an issue where random particles appear near the bottom line of the matrix, causing chaos when even mi ...

Definition of TypeScript array properties

Having some trouble creating a type for an array with properties. Can't seem to figure out how to add typings to it, wondering if it's even possible. // Scale of font weights const fontWeights: FontWeights = [300, 400, 500]; // Font weight alia ...

Display the output from the print_r function in PHP

Can anyone show me how to display the contents of this PHP array? I am a beginner and struggling with using print_r to echo the results. Thank you in advance. Below is the test result: Array ( [html_attributions] => Array ( ) [result] ...

Verifying the Redux saga test plan's functionality by testing a reducer with a specific state branch

I'm facing some challenges in properly testing my saga. The issue arises because when the saga is running, the reducer is mounted at state: {...initialState}, while my saga select effects expect the reducer to be mounted at state: {authentication: {.. ...

What is the best way to continuously add new elements to a dictionary within a loop?

Currently, I am in the process of developing a program that extracts names and statistics from a file. Each line in the file represents an individual and their corresponding stats. To create a dictionary where each person's last name is a key linked t ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...

Running a loop to utilize data from an array of objects within a Protractor it() spec

I am currently in the process of setting up an end-to-end test suite with specifications to assess the functionality of opening a file within the application. My goal is to collect performance data for each test specification, focusing on variables such as ...

Is `TypeDefinition for React v15.0` compatible with React v0.14.7?

Within the project I am currently working on, we have incorporated React v0.14.7. After using npm, I executed the following command: npm install --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccbea9adafb88cfce2fdf8e2fb ...