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 = 5
TS 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 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 )
}
}