What are data types in TypeScript?
Definition
A data type holds information about the type of data stored in a variable, e.g., number, string, boolean, etc.
Syntax
To provide a data type for a variable, you have to use the : symbol. In the code snippet below, number is the data type of variable a:
let a:number = 10
Arrays
For arrays, the data type is provided in the form type[].
In the code snippet below, string[] is the data type for the fruits array:
let fruits:string[] = new Array("apple","orange")//printing the first fruitconsole.log(fruits[0])
Parameters
You also need to specify the data type for function parameters. In the code snippet below, string is the data type for parameter name:
function hello(name:string){console.log(`Hello ${name}`)}//calling the functionhello("John")
Return type
You must also specify the data type of the value to return from a function.
Note: The
voidtype is used for functions that do not return a value.
In the following code snippet, the return type is string:
function hello():string{return "hello world !!!"}//printing the output returned from function.console.log(hello())
Primitive and user-defined types
TypeScript provides two different kinds of data types: primitive and user-defined.
Primitive data types
Primitive data types hold data that is not an object.
TypeScript provides three common primitives: string, number, and boolean.
string: Represents a sequence of characters.
let a:string = "This is a string"
number: Representsinteger,float, anddoublevalues.
let a:number = 10
let b:number = 10.10
boolean: Representstrueorfalse.
let isLoggedIn:boolean = true
User-defined types
User-defined types in TypeScript can be implemented as an Object or Interface.
Object
An Object type contains key:value pairs separated by a comma ,.
In the code snippet below, the greet function accepts the parameter person as an Object data type:
// passing object as parameter typefunction greet(person: { name: string; age: number }) {return "Hello " + person.name;}//printing the value returned from function and passing object as parameterconsole.log(greet({name:"John",age:30}))
Interface
Interface is used to create a blueprint for data-type objects so that multiple objects can be made. For example, in the code snippet below, Person is an Interface that consists of name and age and can be used to create multiple objects:
//creating interface Personinterface Person {name: string;age: number;}// function which accepts parameter of type interfacefunction greet(person: Person) {return "Hello " + person.name;}// creating a object p, Person as data type.let p:Person = {name:"John",age:30}//passing object p which is of data type interface Person to function callconsole.log(greet(p))