What is the reason for TypeScript's lack of warnings when assigning null to a non-nullable value?

When I specify types on a function in TypeScript, I expect non-nullable behavior by default. However, even though TypeScript versions are supposed to be non-nullable by default, I am not receiving any errors when running a function with null or undefined.

function sayHello(name: string){
  console.log(`Hello ${name}`)
}

In the example above, both sayHello(undefined) and sayHello(null) should result in failure.

However, here is what actually happens in TypeScript 3.8.3:

Hello null
Hello undefined

Interestingly, vsCode does not give any warnings:

https://i.sstatic.net/c4J0i.png

I wonder why TypeScript does not issue a warning when assigning a non-nullable value as null?

Answer №1

Do you happen to possess a tsconfig.json file? If that's the case, could you describe its contents?

Ensure that your tsconfig.json includes the following configuration (abbreviated for brevity):

{
  "compilerOptions": {
   "strictNullChecks": true
  }
}

According to the TypeScript documentation:

strictNullChecks: enables a stricter null checking mode.

Answer №2

The latest update in TypeScript makes not nullable the default option. An error message will appear during compilation if you try to assign a 'null' to a parameter expecting a 'string':

Argument of type 'null' is not assignable to parameter of type 'string'. ts(2345)

If this error doesn't show up, consider reviewing your compiler settings. It's recommended to enable the strict option.

You can configure this in a tsconfig.json file with the following content:

{
  "compilerOptions": {
    "strict": 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

Exploring the differences between DDB.query and Raw Operation Object in CDK within AWS AppSync Resolver

Currently, I am in the midst of an AWS AppSync project utilizing CDK (Cloud Development Kit) to define my resolvers. While working on this project, I have stumbled upon two distinct approaches for writing DynamoDB query operations within my resolver functi ...

Developing custom events in an NPM package

Developing a basic npm package with signalr integration has been my recent project. Here's how it works: First, the user installs the package Then, the package establishes a connection using signalr At a certain point, the server triggers a function ...

Encountered a Solana Error while handling Instruction 2: custom program error with code 0x1000078

While attempting to create an AMM Pool using the 'ammCreatePool.ts' script from the raydium-sdk repository, I encountered the following error message. I executed the script directly with ts-node src/ammCreatePool.ts and made modifications so that ...

Switching slides in Ionic 4 with a simple button click

I want to switch slides by clicking a button on my presentation. Here is an example code snippet: <ion-slides> <ion-slide> Slide one <ion-slide> <ion-slide> Slide Two <ion-slide> </ion-slides> <butt ...

Tips for utilizing TypeScript to automatically infer that a property within one type is of the same type

Looking to sort an array of items, each with properties of either string or number type, without mixing types for each property: type Item = { prop1: string; prop2: number; prop3: string; prop4: number; } To keep it abstract, I am using propertyNa ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Creating a unique Nest.js custom decorator to extract parameters directly from the request object

I am working with a custom decorator called Param, where I have a console.log that runs once. How can I modify it to return a fresh value of id on each request similar to what is done in nestjs? @Get('/:id') async findUser ( @Param() id: stri ...

Having trouble loading JSON file contents into an array in Typescript

I am struggling to load my API keys from a JSON file named api.json. The file structure is as follows: { "service1": ["apikey1", "apikey2"], "service2": ["apikey1", "apikey2"] } In order to manag ...

Associate the keys of a map interface with an array containing key-value pairs

Consider a scenario where we have an interface For example: interface Person { name: string; age: number ; } We aim to develop a generic function that can take the following parameters const res = Result.combineValues<Person>( { age: 1 ...

Transforming query language from jQuery to Pure JavaScript

I have the following jQuery code that I am attempting to remove and convert into standard JavaScript: $('.switch').click(()=>{ $([".light [class*='-light']", ".dark [class*='-dark']"]).each((i,ele)=& ...

Is it possible for ko.mapping to elegantly encompass both getters and setters?

Exploring the fusion of Knockout and TypeScript. Check out this code snippet: class Person { public FirstName:string = "John"; public LastName: string = "Doe"; public get FullName(): string { return this.FirstName + " " + this.Las ...

Navigate to the logout page automatically when closing the final tab

In order to comply with the requirement, I need to log out the user when they close the last tab on the browser. ngOnInit() { let counter: any = this.cookieService.get('screenCounterCookie'); counter ? ++counter : (counter = & ...

The error message states that the property '$refs' cannot be found on the void type

Attempting to automatically focus on the next input field after typing 1 character. Encountering error: The property '$refs' does not exist on type 'void'. Here is the code snippet: setup() { const autoFocusNextInput = (event, max: ...

Improve the way you manage the active selection of a button

ts isDayClicked: { [key: number]: boolean } = {}; constructor() { } setSelectedDay(day: string, index: number): void { switch (index) { case 0: this.isDayClicked[0] = true; this.isDayClicked[1] = false; this.isDay ...

The nest build process encounters errors related to TypeScript in the @nestjs/config package, causing it

Encountering several issues related to @nestjs/config, causing the npm build command to fail. However, npm run start:dev is still functional despite displaying errors. See below for screenshots of the errors and environment: https://i.sstatic.net/Wxkkn.png ...

What is the best way to perform a conditional check and return a customized object while working with a Promise?

I have developed a provider specifically for handling all Firebase database related requests. In the getUser method, when the data is fetched from the database using .once which returns a promise, if the object is null it currently returns null. This means ...

What is the process for retrieving the chosen country code using material-ui-phone-number?

When incorporating user input for phone numbers, I have opted to utilize a package titled material-ui-phone-number. However, the challenge arises when attempting to retrieve the country code to verify if the user has included a 0 after the code. This infor ...

Filtering a key-value pair from an array of objects using Typescript

I am working with an array of objects containing elements such as position, name, and weight. const elements = [{ position: 3, name: "Lithium", weight: 6.941, ... },{ position: 5, name: "Boron", weight: 10.811, ... }, { position: 6, name: "Carbon", weight: ...

The use of the "declare" keyword is prohibited within the `script setup` section of Vue

I need to integrate the function getCookie into my Vue file. This function is already defined in the HTML file where the Vue file will be injected. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" ...

Convert a fresh Date() to the format: E MMM dd yyyy HH:mm:ss 'GMT'z

The date and time on my website is currently being shown using "new date()". Currently, it appears as: Thu May 17 2018 18:52:26 GMT+0530 (India Standard Time) I would like it to be displayed as: Thu May 17 2018 18:43:42 GMTIST ...