Array type with known and possibly different types:

let day: [number, string];
day = [0, 'Monday']; // valid
day = ['zero', 'Monday']; // invalid: 'zero' is not numeric
console.log(day[0]); // 0
console.log(day[1]); // Monday
day[2] = 'Saturday'; // valid: [0, 'Saturday']
day[3] = false; // invalid: must be union type of 'number | string'

Boolean in TypeScript

A boolean represents the most basic datatype in TypeScript, with the purpose of assigning true/false values.

// set with initial value (either true or false)
let isTrue: boolean = true;
// defaults to 'undefined', when not explicitly set
let unsetBool: boolean;
// can also be set to 'null' as well
let nullableBool: boolean = null;

Intersection Types

A Intersection Type combines the member of two or more types.

interface Knife {
cut();
}
interface BottleOpener{
openBottle();
interface Screwdriver{
turnScrew();
}
type SwissArmyKnife = Knife & BottleOpener & Screwdriver;
function use(tool: SwissArmyKnife){
console.log("I can do anything!");
tool.cut();
tool.openBottle();
tool.turnScrew();
}

Types in function arguments and return value. Number

When you create a function in TypeScript you can specify the data type of the function’s arguments and the data type for the return value

Example:

function sum(x: number, y: number): number {
return x + y;
}

Here the syntax x: number, y: number means that the function can accept two arguments x and y and they can only be numbers and (…): number { means that the return value can only be a number.

Usage:

sum(84 + 76) // will be return 160

Note:
You can not do so

function sum(x: string, y: string): number {
return x + y;
}

or

function sum(x: number, y: number): string {
return x + y;
}

it will receive the following errors:

error TS2322: Type ‘string’ is not assignable to type ‘number’ and error TS2322:

Type ‘number’ is
not assignable to type ‘string’ respectively

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: Tuple in TypeScript

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password