How to use float type in typescript? – Typescript

Ali Hasan
react-typescript reactjs

Quick Fix: JavaScript and TypeScript consider number as a generic type that can hold both integers and floats. TypeScript can infer the type based on the assigned value (e.g., const myFloat = 1.01;). Alternatively, you can explicitly annotate the type as number, especially when assigning values later (e.g., let myFloat: number; myFloat = 1.01;).

The Solutions:

Solution 1: Primitive and Object Types in TypeScript

TypeScript does not distinguish between integer and float types; it only has a single `number` type. For very large numbers, it provides `BigInt`.

It’s important to use lowercase type names for primitive values. Instead of `Number`, use `number`. `Number` is a TypeScript type for an object that wraps around a `number` primitive and provides additional methods.

TypeScript can infer the type of a value when it’s initialized. For instance, `const myFloat = 1.01;` will be inferred as a `number`. When you can’t provide a value during variable declaration, you can specify the type annotation as follows:

let myFloat: number;

Then, at a later point, you can assign a value:

myFloat = 1.01;


Can we use Number or is there something else type-specific?

JavaScript and TypeScript only have a single numeric type number.

What is the correct way to declare a number?

Use number for the type, but always use lowercase.

How can I declare a number without a value at first?

Use the type annotation syntax, like let myFloat: number;.

Video Explanation:

The following video, titled "Understanding the Number Type in TypeScript - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Explanation of what is a number type in TypeScript along with examples. FREE JavaScript Cheat Sheet ...