[내일배움캠프 TIL] 59일차

Jaehyeon Ye·2023년 1월 19일
0

오늘 새로 배운 것

정적 언어 / 동적 언어 프로그래밍

변수 선언시 데이터 타입을 지정하냐 안하냐에 따라 지정하면 정적언어, 지정 안하면 동적 언어

정적 언어는 C / Java / Typescript 등이 있고
동적 언어는 python, Javascript 등이 있다.

런타임 에러 / 컴파일 에러

런타임 에러 : 프로그램 실행 중 발생하는 에러
컴파일 에러 : 문법을 잘못 입력하여 컴파일할 수 없는 에러

함수

function foo():number{
	...
}

리턴값이 있으면 리턴값의 타입을 위와 같이 쓰고 리턴값이 없으면 위의 number 타입 자리에 void를 써준다.

function hello(name?: string){
  return `hello, ${name||'world'}`;
}

name이 없어도 world로 리턴될 수 있지만 에러가 나는 이유는 name을 명시적으로 작성해주지 않았기 때문이다. 에러가 나지 않게 하려면 위와 같이 옵셔널 파라미터라는 표시로 ?를 붙여줘야한다.

function add(...nums: number[]){
  return nums.reduce((result, num)=>result+num, 0);
}

나머지 매개변수의 타입을 지정해주는 모습이다. 배열 형태로 기입한다.

interface User{
  name: string;
}

const Sam: User = {name: 'Sam'}

function showName(this:User, age:number, gender:'m'|'f'){
  console.log(this.name, age, gender)
}

const a = showName.bind(Sam)
a(30, 'm');

인터페이스(Interface)

예:

interface IsAdult{
  (age:number):boolean;
}

const a:IsAdult = (age)=>{
  return age > 19;
}

제너릭(Generics)

예1:

function getSize<T>(arr:T[]):number{
  return arr.length
}

const arr1 = [1,2,3];
getSize<number | string>(arr1);

const arr2 = ['a','b','c']
getSize<string>(arr2);

제너릭 타입을 보편적으로 'T'로 쓰고 밑에서 경우에 따라 number인지 string인지를 선언해줄 수 있다.

예2:

interface Mobile<T>{
  name:string;
  price:number;
  option:T;
}

const m1: Mobile<{color:string, coupon:boolean}>={
  name:'s21',
  price: 1000,
  option:{
    color:'black',
    coupon:false,
  },
};

const m2: Mobile<string>={
  name:'s20',
  price:900,
  option:'none',
}
  

같은 Mobile 타입을 가지지만 예1과 같이 option을 다르게 한 object를 만들 수 있다.

예3:

function foo<T extends {property:string}>(params:T):string{
  return stringTypeResult;
}

extends로 추가 속성과 타입을 추가할 수 있다.

profile
FE Developer

0개의 댓글