What is the method for specifying the return type of an anonymous function?

I'm interested in utilizing tuples as return types in array.map(..) without the need to declare their types in advance, particularly for my concise functions that typically yield tuples with just two elements.

How can I accurately specify the return type of an anonymous function?

Answer №1


// sample input
let words: string[] = [ "apple", "banana" ]

// potential type definition
type Pair = [string, number];

// detailed function declaration
function wordLength(word: string): Pair
{
    return [word, word.length];
}

// various approaches using .map() 
// yielding the same outcome for syntax variation

let result0 = words.map( w => wordLength(w) );

let result1 = words.map( (w: string): Pair => wordLength(w) );

let result2 = words.map( (w: string): Pair => 
{
  return [w, w.length]
});

let result3 = words.map( (w: string): [string, number] => 
{
  return [w, w.length]
});

let result4 = words.map( (w): [string, number] => 
{
  return [w, w.length]
});

let result5 = words.map( (w): [string, number] => [w, w.length] );


Test it live with immediate error highlighting www.typescriptlang.org

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

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Can one service be injected into another service and vice versa simultaneously?

I encountered a challenging scenario in an actual project where I found the need for two services to access each other's properties and methods. Despite my limited expertise in Angular, I wondered if this is even possible? I made an attempt, but unfo ...

Conceal the highlighting of the column headers in PrimeNG DataTables

Is there a way to remove the blue highlight in the column header that remains after sorting? I want to prevent the column from being selected when clicked for sorting purposes. Can an attribute be used to disable column selection, like how 'selection ...

Implementing External Libraries with Angular: A Guide to Utilizing Tools for DOM Creation and Management

I am currently in the process of developing an Angular >2 library that serves as a wrapper for another library originally coded in vanilla/plain JavaScript. The external library in question is a gallery that performs actions such as DOM manipulation (c ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

Angular Universal build stuck on rendering page while waiting for API response

I'm currently developing a compact web application using the angular universal starter in combination with pokeapi. To enhance performance and reduce API requests, I intend to implement pre-rendered pages since the data displayed remains mostly static ...

Instructions for adding a method to a prototype of a generic class in TypeScript

My current challenge involves adding a method to a prototype of PromiseLike<T>. Adding a method to the prototype of String was straightforward: declare global { interface String { handle(): void; } } String.prototype.handle = functi ...

Angular input material with a stylish twist

How can I style all inputs on the Angular Material input component (matInput) using Typescript? I attempted to implement this solution, but it only affects the first element. ngAfterViewInit () { const matlabel = this.elRef.nativeElement.querySelecto ...

In the Angular Google Maps API, is it possible to update the attributes of <agm-marker> directly within the TypeScript code?

Currently, I am fetching markers from the database and displaying them on a map using Angular Google Maps (AGM) by utilizing the <agm-marker> tag. In my code snippet below, you can see how I fetch and store the markers in an array named markers in t ...

What steps should I take to ensure that an input field triggers a customized query on a JSON API?

I have integrated a Heroku-based Twitter API with my web application, using Angular Material table and other related components. My goal is to allow users to input a string query and update the displayed results based on that input (with debounce applied) ...

typescript method searching for and merging all keys starting with the specified prefix

Take a look at this object: https://i.sstatic.net/V0xvI.png Where each property in system(1) holds tridimensional coordinates. Is there a more efficient method to consolidate properties with the same prefix without nesting loops within loops? My goal is ...

My eslint quote rules seem to be disregarded by Visual Studio Code

I am facing an issue with Visual Studio Code not following my eslint rules for my typescript project, particularly with quoting. More information about the configurations of my project can be found here: Typescript: Why doesn't Visual Studio Code repo ...

Utilizing typescript to isolate specific functionality from a class without extending it

Imagine a scenario where I have a class with different areas of functionality: export class TreeTable extends someOtherClass { constructor(){ super.constructor(); } //========= area 1 of functionality ==== itemRightClick(){this.contex ...

Tips for concealing a react bootstrap modal while simultaneously executing the save function

When I click on the button with the onClick event set to {this.props.onHide}, the Modal is hidden successfully. However, I also need to execute the save function. When I try calling the save function along with the props, the save function is executed but ...

Comparing TypeScript and C++ in terms of defining class reference member variables

class B; class A { A(B b_) : b{b_} {} B &b; }; In C++, it is possible to have a reference member variable like 'b' in class A. Can the same be achieved in TypeScript? Alternatively, is there a specific method to accomplish this in ...

The outcome from using Array.reduce may not always match the expected result

After discovering an unexpected behavior in Typescript's type-inference, I suspect there may be a bug. Imagine having a list of the MyItem interface. interface MyItem { id?: string; value: string; } const myItemList: MyItem[] = []; It's ...

NexusJS threw an error stating that the Class constructor GraphQLNonNull cannot be called without using the 'new' keyword

While attempting to learn Nexus, I encountered some issues. I created an index.ts file with the following code: const User = objectType({ name: 'User', definition(t) { t.id('id') t.string('name') } }) export co ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Ensure that the types of objects created by spreading are checked

When we spread two different types of objects to compose a new object in TypeScript, the type-checking is not automatically enforced. So how can we make sure that TypeScript performs the necessary checking? type TypeA = { id: number; } type TypeB = { ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...