What's the deal with `void` in TypeScript? Can anyone explain to me why I see the result from

let bar: void;
bar = 2;

I'm a bit confused, can you clarify this for me? I understand when we use void with LET.

However, in a scenario like this:

function test(message): void {
  console.log(message);
}

test("hi");

we still get the output "hi". Why is that?

Answer №1

In defining a function, the last type specifies the type of value that it returns.

You might be wondering why this is necessary.

function test(msg: string): void {
  console.log(msg);
}

This particular function doesn't return anything.

let myVar: void = test("hello!");
console.log(myVar);

When you try to assign a value to myVar, it will be undefined because the function has no return value. This concept is illustrated in this example from Typescript.

let unusable: void = undefined;

So what does "return" mean? It refers to the data that a function sends back after being executed. For example:

function idk(): string {
   return "Hello World!";
}

When I call this function, it returns a string.

let myVar: string = idk();
console.log(myVar);

You can learn more about the concept of returning values in functions from this documentation on returning values by MDN.

Answer №2

I find myself a bit perplexed while attempting to comprehend

I'm not quite grasping it, could you please explain. I understand when we use void with LET - got it

however, if I am interpreting it correctly in my mind, the latter part of the query depicts void as the return type of a function (essentially nothing) whereas the former segment demonstrates a void variable, which in Typescript is restricted to only null or undefined as values.

The latter portion functions effectively because the function does not attempt to return anything. It does not acknowledge "void" as an argument. The type of message is untyped, hence essentially any object would be permissible.

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

Is there a way to store session variables in Angular without the need to make an API call?

I am currently working with a backend in PHP Laravel 5.4, and I am looking for a way to access my session variables in my Angular/Ionic project similar to how I do it in my Blade files using $_SESSION['variable_name']. So far, I have not discove ...

Angular modules are designed to repeat chunks of code in a

Whenever I scroll the page, my function pushes items to an array. However, I am facing an issue where the pushed items are repeating instead of adding new ones. Solution Attempt onScroll(): void { console.log('scrolled'); var i,j,newA ...

Incorporate JavaScript Library into StencilJs Using TypeScript

Recently, I decided to incorporate a JavaScript library called Particles.js into my project. The process involved importing it and initializing it within my component: import { Component, h } from '@stencil/core'; import * as particlesJS from &a ...

Dragging element position updated

After implementing a ngFor loop in my component to render multiple CdkDrag elements from an array, I encountered the issue of their positions updating when deleting one element and splicing the array. Is there a way to prevent this unwanted position update ...

Angular 6 is throwing an error message stating that it cannot access the 'image' property of an undefined object

Having trouble retrieving the details, as it is rendering to the dom with an undefined error. Check out this image for reference: https://i.sstatic.net/YB2Lf.jpg Welcome to the Book Details Component export class BookDetailsComponent implements OnInit { ...

How can two components share the status of their side bar being open or closed?

I am currently working on a project using React and TypeScript. My setup is displayed below, where I have a button in the "Topbar" that, when clicked, should minimize both the sidebar and elements on the left side of the Top Bar. How can I properly pass ...

There seems to be a mismatch in compatibility between the register() function in react-hook-form and the native input types

Currently, I'm in the midst of a React project that utilizes TypeScript along with react-hook-form. At one point in my code, I am making use of the provided function register(), which should be implemented as follows according to the official document ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. https://i.sstatic.net/QNdpJ.png After creating the code in codesandbox and previewing the output, I noticed that the title is not a ...

Struggling to transfer array data from service to component

I am currently working on passing an array from service.ts to a component. My goal is to display the array elements in a dialog box. However, I encountered a Typescript error TypeError: Cannot read property 'departmentArr' of undefined. I am str ...

Guide to invoking an API in Next.js 13 by utilizing specific variables within a client component

I currently have a collection of products that are accessible on my website through a straightforward function within a server component. async function getData() { const res = await fetch(`${apiPath}`); const data = (await res.json()) as PackProps ...

Are you looking for a streamlined method to create styled components with MaterialUI?

I am exploring ways to easily define convenient components in my application utilizing Material-UI. After referring to an example from the Material-UI documentation for Appbar, I attempted to incorporate some React components for better readability. My c ...

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

Encountering a Problem on Heroku: TypeScript Compilation Error with GraphQL Files - TS2307 Error: Module 'graphql' Not Found or Its Type Declarations Missing

While trying to compile my typescript project with graphql files for deployment on Heroku, I encountered the following error message: node_modules/@types/graphql-upload/index.d.ts(10,35): error TS2307: Cannot find module 'graphql' or its correspo ...

Angular routerLink causes ngOnInit to be triggered only once

I have come across numerous questions similar to mine, however, the majority are linked to params. The answers provided did not aid in resolving my specific issue. Essentially, the problem I am facing is as follows: After a user logs in, their username is ...

Issue with Typescript: For in loop not identifying object properties

Currently, I am utilizing a loop with for in to iterate through a list of Meeting objects named allMeetings. Inside this loop, I am populating another list called allEvents, where non-Meeting objects will be stored. However, when attempting to access the p ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

The 'XXX' property is not found in 'YYY' type but is necessary in 'ZZZ' type

I'm struggling with setting up class properties in TypeScript. Here is the TypeScript code that I am working on: export class myClass { a: number; b: number; public getCopy(anotherClass: myClass): myClass { return { a: anotherClass.a, ...

When using TypeScript, the reducer function may not be recognized, causing the type to display as 'any

I am a beginner in Typescript and we are implementing hooks in our React application. We have a shared thunk action creator that triggers one of the actions. appSlice.ts type ThunkOptions = { method: number, api_url: string, body: any | null } ...

Displaying TypeScript issues across the entire project in WebStorm allows for a comprehensive overview

Is it possible to have Webstorm consistently report all TypeScript errors across an entire project without having to open each individual file? I prefer using the language service for performance reasons rather than running tsc as a task. I've notice ...

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...