“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

TypeScript primitive data types

This time, I’m going to introduce you to TypeScript’s common types and some basic concepts. I hope you can get a feel for TypeScript. First give a link to everyone, call me Lei Hong!

Primitive data type

basis

There are two types of JavaScript:

  • Raw data type (Primitive data types)
  • Object type (Object types)

Primitive data types include Boolean, numeric, string, null, undefined, and the new type Symbol in ES6 and BigInt in ES10.

Next we’ll cover the rest of the Boolean, numeric, string, null, undefined, and the new type Symbol in ES6 and BigInt in ES10.

go go go

Boolean value

Booleans are the most basic data types. Let’s show some examples of how Boolean types are defined in TypeScript. Note that objects created using the constructor Boolean are not Booleans! It’s a Boolean object

let b: boolean = false;
Copy the code

Of course you can declare it that way

let b1: Boolean = new Boolean(1);
Copy the code

And you can do that or you can call it directly

let b2: boolean = Boolean(1);
Copy the code

In TypeScript, Boolean is the basic type in JavaScript, and Boolean is the constructor in JavaScript. The other basic types (except null and undefined) are not mentioned here.

The numerical

Define numeric types using number:

let num1: number = 6;
// Binary representation in ES6
let num2: number = 0b1010;
// Octal notation in ES6
let num3: number = 0o744;
Copy the code

0B1010 and 0O744 are binary and octal representations in ES6, which are compiled to decimal numbers.

string

Use string to define a string type:

let name: string = 'Hello World';
Copy the code

You can also use template strings

// Template string
let sentence: string = `Hello, my name is ${myName}.
Copy the code

A null value

JavaScript has no concept of Void values, and in TypeScript we use Void to represent functions that do not return any value:

function say(): void {
    alert('Hello World');
}
Copy the code

Null, and Undefined

In TypeScript, null and undefined are used to define these two primitive data types:

let u: undefined = undefined;
let n: null = null;
Copy the code

Symbol

Using the Symbol() function, we can declare a Symbol variable. Do not use the new command (it is a primitive data type after all).

let sym = Symbol("key");
Copy the code

BigInt (new type in ES10)

With BigInt, integer overflow problems are eliminated.

// bigint Specifies a number followed by the letter n
let bigint1: bigint = 999999999999999999n
Copy the code

It can also be used like Boolean

// You can also use the BigInt function
let bigint2: bigint = BigInt('9999999999999')
Copy the code