TIL. Type Annotations, inference

chloe·2021년 4월 25일
0

Typescript

목록 보기
8/8
post-thumbnail

Type Annotations

Code we add to tell Typescript what type of value a variable will refer to

Type Inference

Typescript tries to figure out what type of value a variable refers to

🧐hmmm..I guess that the definition of both are very similar.
But intersting thing about type annotations and type inference is that they are kind of at odds with each other. Let's check the below.

* Type annotations: we(developers) tell Typescript the type

* Type inference: Typescript guesses the type


Object Literal Annotations

// built in objects
let now: Date =new Date();
//Array
let colors:string[]=['red','green']
let numbers:number[]=[1,2,3];
let truths:boolean[]=[true,true,false]
//Object literal
let point :{x:number; y:number} ={
x:10,
y:20
};

Annotation for a function

const logNumber: =(i : number) => void =(i:number) =>{
  console.log(i);
};

(i : number) => void => That's the annotation that is trying to tell typescript what type of value we are going to assign
(i:number)=> Everything on the right hand side of the equals is the actual function

When to use Annotations

1)Functions that returns the any type

Any type essentially means that typescript has no idea what type of value is being returned

2) When we declare a variable on one line and initalizate it later

let words=['red','green','blue'];
let foundWord:boolean; //(declare)

for(let i=0; i<words.length; i++){
  if(words[i]==='green'){
    foundWord=true; //initalizate it later
  }
}

3)Variable whose type cannot be inferred correctly

let numbers=[-10,-1,12];
let numberAboveZero:boolean | number =false;

for(let i=0; i<numbers.length; i++){
  if(numbers[i]>0){
    numberAboveZero=numbers[i];
  }
}

Type annotations for functions : Code we add to tell typescript what type of arguments a function will receive and what type of values it will return
Type inference for functions: Typescript tries to figure out what type of value a function will return

const add=(a:number,b:number) : number=>{
  return a+b //the function is going to return a number
  
};

const logger=(message:string):void=>{
  console.log(message);
  return undefined
};
//we use void right here to say there will be no return value from this function, if we accidentally return something,, we'll get an error message that says you can't return anything at all

const throwError=(message:string): never=>{
  throw new Error(message);
  //that means that we are never going to actually reach the end of this function so we're never going to execute the function completely
  // we only annotate a function with type never when we really truly never expect a function to return anything ever.
};

Destructuring with Annotations

const todaysWeather={
  date: new Date(),
  weather:'sunny'
};
const logWeather=({date,weather}=>{ date:Date, weather:string}):void =>{
  console.log(date); 
  console.log(weather);
  //we should seperate the destructuring and annnotations
}

Annotations Around Objects

const profile={
  name:'alex',
  age:20,
  coords:{
    lat:0,
    lng:15
  },
  setAge(age:number):void{
    this.age=age;
  } 
};

const {age,name}:{age:number; name:string} =profile;
const{coords:{lat,lng}}:{coords:{lat:number; lng:number}}=profile;
profile
Front-end Developer 👩🏻‍💻

0개의 댓글