What are the various methods of specifying function types in TypeScript?

I've noticed that in Typescript you can easily declare a function type using the declare keyword. For example:

declare function test1(name: string): true

const t1 = test1('t') // true

Alternatively, you can also use the arrow notation:

const test2 = (name: string) => true

const t2 = test2('t') // boolean

Both of these methods work perfectly fine without any compiler errors. However, it seems like the final inferred type is different even when specifying them to be true at the same time?

On the other hand, if I change the return type true to a general primitive type, such as string, the second example will give me an error:

declare function test1(name: string): string // ok

const test2 = (name: string) => string // error: 'string' only refers to a type, but is being used as a value here.

It appears that for the "arrow function notation" type, you need to specify the return result/type to be a specific result. Using generics does not make sense either for the final result:

declare function test1<T>(name: T): T // ok

const test2 = <T>(name: T) => T // error: 'T' only refers to a type, but is being used as a value here.

However, neither of them "looks like a type" in the sense that you can define them using the const keyword (in the second example, which is usually for declaring a variable). You can then call them like a normal function, and they will give you the return type/result without implementing the actual details:

test1('xxx')
test2('xxx')

So my question is:

  • Are they truly types (like type aliases)? Do they have specific names in Typescript?
  • Is there any distinction between these two notations? How should we properly use them?

Answer №1

Declaring something in TypeScript informs the compiler that a function/variable/class will be present at runtime but will be removed during compilation. The type or function signature of the entity is specified:

// equivalent declarations
declare function test1(name: string): true
declare const test1: (name: string) => true
test1('') // output true

Creating test2 involves defining an arrow function with an implementation that will exist at runtime because the declare keyword is not used:

// equivalent declarations
function test2(name: string) {
  return true
}
const test2 = (name: string) => true
test2('') // result is boolean

If the return type is not explicitly specified, TypeScript will infer the return type to be boolean. To explicitly state that it is true:

function test3(name: string): true {
  return true
}
const test3 = (name: string): true => true
test3('') // output true

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

What exactly is the purpose of the colon in JavaScript's import statement?

Looking at the following example. import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' I am puzzled by the use of colons and I am unsure about where the imported files are being referenced from. ...

What causes tsc to generate different json files based on its execution location?

Scenario: You have a typescript project set up to generate JSON files. The tsconfig.json is properly configured and all dependencies are in place. You've even referred to this related Q&A and ensured that your typescript files are importing the json f ...

The term 'required' is not recognized as an identifier. There is no member by the name of '__type' in the definition

When working on my HTML template in the visual code editor, I encountered the need to declare a variable with type any? https://i.stack.imgur.com/Jq5az.png product-form.component.html <div class="row"> <div class="col-md-6"> <for ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Getting the value of the chosen option from one component and passing it to another component in Angular 8

How can I pass the selected option value from the login component to the home component without using local storage? When an option is selected in the login component, I want that value to be displayed in the home component. Below is the code snippet: Lo ...

The onClick event in HostListener is intermittent in its functionality

While attempting to create a dropdown box in Angular by following these examples, I am encountering inconsistent results. Below is the code I have used: HTML <button (click)="eqLocationDrop()" id="eqLocButton"><i class="fas fa-caret-down">< ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

The assertion error `args[3]` must be an integer value, but it failed to meet the requirement

Software Version: v12.19.0 Operating System Platform: Linux ayungavis 5.4.0-48-generic #52~18.04.1-Ubuntu SMP Thu Sep 10 12:50:22 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux Subsystem: Steps to Reproduce the Issue I attempted to follow the tutorial provided ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

A JavaScript function written without the use of curly braces

What makes a function good is how it is declared: export declare class SOMETHING implements OnDestroy { sayHello() { // some code to say hello } } However, while exploring the node_modules (specifically in angular material), I stumbled up ...

Click function for mat-step event handler

Is it feasible to create a click event for the mat-step button? I want to be able to add a (click) event for each mat-step button that triggers a method. Essentially, I am looking to make the mat-step button function like a regular button. You can find mo ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

Locate the nearest upcoming date and time to today's date in the JSON response

I am currently working with an API that provides a response containing the `start_time` field in JSON format. My goal is to extract the ID from the JSON object whose next date time is closest to the current date and time, excluding any dates from the past. ...

Error: The function call does not match any of the overloads. 'VueRouter' is not recognized

I'm new to TypeScript and currently trying to implement vue-router in my project. Encountering the following errors: Error TS2769: No overload matches this call in source\app\main.ts(3,3). Overload 1 of 3, '(options?: ThisTypedCompon ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

The use of URL embedded parameters in @angular/http

Currently, I am utilizing a backend system that accepts search query parameters in both the ?-notation and the url-embedded format. I understand that I can use tools like URLSearchParams/RequestOptionsArgs to send requests to . However, I am curious about ...

The data type 'Event' cannot be assigned to the data type 'string' in this context

Recently diving into Angular, I came across a stumbling block while working through the hero tutorial. The error message that popped up was: Type 'Event' is not assignable to type 'string' You can see the error replicated here. ...

Error Message: Unable to access 'map' property of undefined in TSX file

Component for displaying attendees in an activity interface IProps { attendees: IAttendee[] } export const ActivityListItemAttendees: React.FC<IProps> = ({attendees}) => { return ( <List horizontal> {attendees.ma ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

Is it normal that aws-eventbridge-lambda does not generate a Lambda function?

I've been experimenting with the AWS CDK (Typescript) to enhance my knowledge. I'm interested in setting up a lambda function to run daily at a specific time or at intervals of N minutes. Since I anticipate having multiple functions, it would be ...