Daniel
Daniel

Reputation: 1472

Allow null to be used like a number in typescript

I am wondering if there is an option that allows null to be used like a 0 in typescripts compiler options.

I know I can cast null to a number by doing Number(null), but I would prefer just being able to use variables that can be null without doing that.

A similar solution to Number(null) (null??0) (answered here: Allow nullable operands in less- or greater-than comparisons in TypeScript) is a code work around; however, I am looking for a typescript compiler option that allows for this.

example of what I am looking to be able to do. (without getting a type error)

const x = null

console.log(x>0)
console.log(x<0)
console.log(x<=0)
console.log(x>=0)

Javascript has no problem treating null as 0.

(turning strict mode off allows for this, but I want to be able to use strict mode and JUST have this turned off)

Upvotes: 0

Views: 923

Answers (1)

Nullndr
Nullndr

Reputation: 1827

You could set strictNullChecks into your tsconfig.json, but you have to annotate the type

const x: number = null

But please, pay attention, x is and will be null for JS.

Upvotes: 1

Related Questions