Posts > TS Basic: Type Annotation
July 9, 2023
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 = 5TS allows to specify the type of both the input and the output
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 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.
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.
the optional property is defined by using ? after the property name.
type Person = {
	first : string,
	last? : string,
}πoptional property is assigned as undefined
| operatorfunction printId( id : number | string ){
	console.log(id);
}
printId(123); // no error
printId('abcd'); // no errorcan 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 )
	}
}