TypeScript: Core Data Types

Core Data Types

  • number: 1, 5.3, -10
  • string: 'Hi', "Hi", `Hi`
  • boolean: true, false
  • object: {age: 30}
  • Array: [1, 24, 24]

Example with Unspecified Data Type

Let's take a look at the code below. The function add accepts two parameters and returns the result of n1+n2. In example 1, we are passing two numbers, which results in 7.8. However, in example 2, since we are passing a string and a number, the two values are then concatenated instead of added.

// Risks of 'any' type
function add(n1, n2) {
  return n1 + n2;
}

const number1 = 5;
const number2 = 2.8;

const result1 = add(number1, number2);

console.log('Without Defined Data Type:');
console.log('Result 1: ');
console.log(result1);

console.log('------------');

const number3 = '5';
const number4 = 2.8;

const result2 = add(number3, number4);

console.log('Result 2: ');
console.log(result2);

Console Logs:

Without Defined Data Type:
Result 1: 
7.8
------------
Result 2: 
52.8

StackBlitz Link


Example with Defined Data Type

In order to prevent passing values with incorrect data types to our function, we can specify the data type that the function is expecting. Let's look at the example below. Note that passing a string to this function will cause a compile-time error. Thus, the last few lines of the code are commented out.

// With Defined Data Type
function addWithType(n1: number, n2: number) {
  return n1 + n2;
}

const number5 = 3;
const number6 = 6.4;

const result3 = addWithType(number5, number6);

console.log('With Defined Data Type:');
console.log('Result 3: ');
console.log(result3);

// const number7 = '5';
// const number8 = 2.8;

// const result4 = addWithType(number7, number8);

// console.log('Result 4: ');
// console.log(result4);

Console Logs:

With Defined Data Type:
Result 3:
9.4

StackBlitz Link


View Parent Post: TypeScript: Everything You Need to Know