Primitive data type

wang xiao bo 's photo
wang xiao bo
·Sep 7, 2021·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

The original data types include: Boolean value, numeric value, string, null, undefined, and the new type Symbol in ES6 and the new type BigInt in ES10.

Boolean value Boolean value is the most basic data type. In TypeScript, use boolean to define the Boolean value type:

let IsOver: boolean = false

// compile passed
// The following agreement does not emphasize the code fragments that compile errors, and the default is to compile through

Note that the object created using the constructor Boolean is not a Boolean value:

let newBoolean: boolean = new Boolean(1);

// Type 'Boolean' is not assignable to type 'boolean'.
//   'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible.

In fact, what new Boolean() returns is a Boolean object: Calling Boolean directly can also return a boolean type:

let newBoolean: Boolean = new Boolean(1);
let createdByBoolean: boolean = Boolean(1);

In TypeScript, boolean is the basic type in JavaScript, and Boolean is the constructor in JavaScript. Other basic types (except null and undefined) are the same, so I won’t repeat them here.


let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
// Binary notation in ES6
let binaryLiteral: number = 0b1010;
// Octal notation in ES6
let octalLiteral: number = 0o744;
let notANumber: number = NaN;
let infinityNumber: number = Infinity;

Compilation result:

var decLiteral = 6;
var hexLiteral = 0xf00d;
// Binary notation in ES6
var binaryLiteral = 10;
// Octal notation in ES6
var octalLiteral = 484;
var notANumber = NaN;
var infinityNumber = Infinity;


let myName: string = 'Bobo';
let myAge: number = 30;

// // template string
let sentence: string = `Hello, my name is ${myName}.`;

Compilation result:

var myName = 'Bobo';
var myAge = 30;
var sentence = "Hello, my name is +myName +."

JavaScript does not have the concept of Void. In TypeScript, you can use void to indicate a function without any return value:

function helloName(): void {
    alert('My name is Bobo');

It is useless to declare a variable of type void, because you can only assign it to undefined and null (only when --strictNullChecks is not specified):

let unusable: void = undefined;

Null and Undefined

let u: undefined = undefined;
let n: null = null;

The difference from void is that undefined and null are subtypes of all types. That is to say, variables of undefined type can be assigned to variables of type number:

// No error
let num: number = undefined
let u: undefined;
let num: number = u;

// error
let u: void;
let num: number = u;
// Type 'void' is not assignable to type 'number'.
Share this


JavaScript Ruby on Rails