Constants in TypeScript

Constants

TypeScript supports constants using the const keyword. Constants can hold primitive values such as strings, numbers, and booleans. Here’s an example:

const s: string = "constant";

console.log(s);

A const statement can appear anywhere a let statement can.

const n = 500000000;

Constant expressions can perform arithmetic with arbitrary precision.

const d = 3e20 / n;
console.log(d);

A numeric constant doesn’t have a type until it’s given one, such as by an explicit conversion.

console.log(BigInt(d));

A number can be given a type by using it in a context that requires one, such as a variable assignment or function call. For example, here Math.sin expects a number.

console.log(Math.sin(n));

To run the program, save the code in a .ts file and use ts-node to execute it, or compile it to JavaScript using tsc and then execute it.

To run the code using ts-node:

$ ts-node constant.ts
constant
6e+11
600000000000n
-0.28470407323754404

Or compile and run:

$ tsc constant.ts
$ node constant.js
constant
6e+11
600000000000n
-0.28470407323754404

Now that we can run and build basic TypeScript programs, let’s learn more about the language.