What is the reason behind TypeScript compiler not throwing an error when a function's return type is defined as a number but the function actually returns undefined

Why does TypeScript not show an error when a function returns null or undefined while the function's return type is number.

//gives error
//Error : A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)
function add1(a: number, b: number): number {}


// no error
function add2(a: number, b: number): number {
  return undefined;
}

// no error
function add3(a: number, b: number): number {
  return null;
}

Answer №1

When the compiler option strictNullChecks is turned off, no errors are encountered during Type Checking. However, enabling this option will prompt Typescript to display errors for the functions add2 and add3.

To learn more about this, you can visit: strictnullchecks-off and strictnullchecks-on

Answer №2

To make your TypeScript compile more strict, insert "strict":true within the "compilerOptions" section of tsconfig.json.

Answer №3

As mentioned by @S.M earlier, the issue is triggered by the presence of the strict flag as well as the strictNullChecks flag.

Whenever I configure it like this:

"strict": true,

or like this:

"strictNullChecks": true,

TypeScript Compiler (TSC) will throw an error, which is exactly what I anticipate.

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

A personalized iteration function for C++

I possess a collection of objects of type "T" that I aim to iterate through. Each object of type "T" is equipped with two crucial properties: int r; // row number int c; // column number My intention is to create an iterator that permits me to traverse a ...

A guide on integrating the vue3-openlayers plugin into a Nuxt project

I am currently working with Vue3 and have the main.ts file set up as follows: import { createApp } from "vue" import App from "./App.vue"; //In the context of nuxt3, how can I include OpenLayersMap? import OpenLayersMap from "vue3 ...

Using @HostBinding based on the @Input() condition

I'm attempting to link the CSS class foo to my parent component by utilizing @HostBinding based on a condition I evaluate against a dynamic variable. However, I am struggling to get it to function as expected. Here are the different approaches I hav ...

Dealing with nullable properties in Typescript

In my React Component code snippet, I am facing an issue with an optional field that needs to be initialized as undefined. This is causing difficulties when trying to use it after type checking. The problem arises in the context of using typescript version ...

What methods can I use to guarantee that a cloned HTML element retains a specific property during Unit Testing?

During my HTML cloning process, I am using the following code snippet: var clone = document.getElementById('tempID').cloneNode(true); After creating the clone, I need to modify its ID by assigning a new unique identifier with clone['id&apo ...

Fastify: Implementing both public and private routes implemented in your application?

I tried reading through the documentation, but I'm still struggling to grasp how to segregate my routes so that only specific plugins are applied to them. Let me share what I currently have: index.ts import fastify from 'fastify' im ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more ...

Do TypeScript project references provide value when noEmit is used?

To enhance the speed of my editor interaction and reduce the time taken by tsc to run on my TypeScript code, I am considering implementing project references. Many teams have reported substantial performance improvements after incorporating project referen ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Step-by-Step Guide on Incorporating leaflet-control-geocoder into Angular 12.x

After successfully integrating Leaflet into Angular 12 using the following commands: npm install leaflet npm install @asymmetrik/ngx-leaflet npm install --save-dev @types/leaflet I made sure to include the styles: ./node_modules/leaflet/dist/leaflet.css i ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Encountered a React 16 error: Unexpected TypeError stating that this.state.userInput.map is not a valid

I am working on a simple React app where a user can input text and I want to display each character as a list. Here is the progress I have made so far: App Components import React, { Component } from 'react'; import './App.css ...

Typescript monorepo facing issues with module resolution in Next.js projects

In my monorepo with yarn workspaces, I have 2 Next.js projects set up. apps ┣ app-1 ┗ app-2 The problem arises when app-1 needs to import components from app-2. I add app-2 as a dependency in the app-1 project and configure the path in app-1's ...

The imported symbol from the typescript library cannot be found

Currently, I am in the process of developing a React/Redux application using Typescript. My goal is to streamline development by creating libraries for each unique "domain" or "feature" that will contain domain-specific details and provide an API to the ma ...

Type generic in TypeScript

I'm having trouble understanding the code snippet below from redux-form export type DataSelector<FormData = {}, State = {}> = (formName: string, getFormState?: GetFormState) => (state: State) => FormData; export const getFormValues: Data ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...

Resolving TypeScript Problem: Showing Error Alerts from React Hook Form

Currently, I am developing a registration form using react-hook-form within a React application. The form I'm working on includes validation for various fields, and my goal is to show error messages for each field. However, I have hit a bump in the ro ...

Preparing JSON data for use with chart.js leveraging Angular 4 observables

Struggling to make sense of this dilemma, I find myself unable to crack the code. The data retrieved from my API is structured in the following format: "data": [ { "sr_count": 91, "month_name": "October", "month_num": 10, ...

obtain every drop-down choice from Angular 2's selectiongetConfig() function

Within the document, there is a select element as shown below: <select tabindex="1" size="5" name="abc" multiple> <option value>Select a value.</option> <option value>option 1</option> <option value>option 2 ...

The key parameter in the sorted function of Python

I need help understanding the logic behind this Python3 code segment: def length_and_alphabetical(string): """Function to return sort key based on length first, then case-normalized string.""" return (len(string), stri ...