Posts > TS Basic: Type Annotation

TS Basic: Type Annotation

Type annotation is where you can optionally add a type to explicitly specify the type of the variables, function ( parameters and return ), and objects.


// let
let myName : string = 'Matthew';
let age : number = 1;

// const
const size : string = 'small'
const quantity : number = 5


TS allows to specify the type of both the input and the output

Parameter Type Annotation

declare type annotation after each parameter to know/declare what types of parameters the function accepts

function greet( name: string ) {
	console.log(`Hello ${name}`);

greet('Owa'); // 'Hello Owa'
greet(2); // This function only accept string as its parameter
👌type annotation is declared after the parameter

function greet(firstName, lastName){
	console.log(`Hello ${firstName} ${lastName}`)

greet('Owa','Aquino'); // `Hello Owa Aquino`
greet('Owa'); // Expected 2 arguments, but got 1.
👌even you don’t have the type annotation on your parameter. TS will still check that you passed the right number/s of arguments.

Return Type Annotation

return type annotation is added after the parameter list

function getFavoriteNumber(): number {
	// your code
👌much like variable type annotation you usually don’t need a return annotation because TS will infer the function return type based on its return statement.

Anonymous Function

  • when a function appears in a place where TS can be determined how it's going to be called, the parameters of that function are automatically given type
  • contextual typing is a feature that allows the compiler to infer the type of an expression based on the surrounding context.


to define an object type we simply list its properties and their types

const obj = {
	name: string,
	last: string,

// or

function printName(obj: { first: string, last: string }){
	// rest of code
👌in JS if you access properties that don’t exist you get the value undefined rather than a runtime error.

Optional property

the optional property is defined by using ? after the property name.

type Person = {
	first : string,
	last? : string,
👌optional property is assigned as undefined

Union Types

  • allows you to define a value can be one or several types
  • represent a value that can be a different type at different time
  • a union type is defined/created using the | operator

function printId( id : number | string ){

printId(123); // no error
printId('abcd'); // no error

can also be used in an array

function welcomPeople( x: string[] | string ){
	if( Array.isArray(x)){
		console.log('Hello' + x.join('and'))
	} else {
		console.log('Welcome' + x )

Tags 🏷