TypeScript_ 5. 타입스크립트 타입

Eunsu·2022년 2월 22일
0

@ TypeScript

목록 보기
9/14

◼ Typescript Type

  • number => 100, 0.3 , -2
  • string => 'hello', "hello", ` hello``
  • boolean => true, false
  • object => {name:string,age:number}
  • array => Array , [] , Array<string|number>, (string|number)[]
  • tuple => [string,number,undefined]
  • enum => enum Role {ADMIN,READ_ONLY,AUTHOR} // 0,1,2
  • any => 모든 타입이던 상관없음

✔ Type 별 예시

◾ number

//변수 number 정의 
const num : number =10 ;
//함수로서 number 정의
const add =(a:number,b:number) => a+b
const result1 = add(10,50) //60
const result2 = add('hello',10) // Type error

◾ string

let str: string = 'hi';
const strFunc=(name :string) => `hello ${name}` 

◾ boolean

let str: boolean = 'hi';
const strFunc=(name :string) => `hello ${name}` 

◾ object

const user :{
	name : string, 
    age:number,
    hobbies:string[]
} = {
   name: "john",
    age: 30,
    hobby: ["sports", "surf"]}

최초 변수는 타입을 지정해주지 않아도, 자바스크립트가 알아서 타입을 판단한다.

◾ array

배열은 제네릭으로도 정의 할 수 있다.

const arr1 : string[] = [];
const arr2 :Array<string> = [];
//string타입으로 이루어진 배열이고 기본값은 []임.
const arr1 : (string | numner)[] =[1,'hello'];
const arr2 : Array<string |number> = [1,'hello'];
//string or number로 이루어진 배열이고 기본값은 [1,'hello']
let arr3 : (string | number)[] | undefined;
//string or number로 이루어진 배열이거나 undefined

◾ tuple

튜플은 배열의 길이가 고정되고 각 요소의 타입이 지정되어 있는 배열 형식을 의미한다.

let arrType : ['string',number] = ['hello',2]
// 첫번째 배열 index에는 무조건 string, 두번째에는 number가 들어가야 함. 
// 기본 배열도 type에 맞게 지정해줘야 함.

지정해주지 않은 타입을 push 할 경우 애러남.

arrType[2] = 'add items';
//Type error

◾ enum

이넘은 다른언어에서 흔하게 쓰이는 타입으로, 특정 값의 집합이다.

  enum Role {ADMIN, AUTHOR, USER}
const user =  {
  name:'john',
  age:30,
  hobbies:['surf','cooking'],
  role:Role.USER
  }
  console.log(user.role) // 2

인덱스로도 접근이나 변경이 가능하다.

 enum Role {ADMIN=4, AUTHOR=5, USER=6}
 const role = Role[0]
 console.log(role) // 4

◾ any

어떤 타입이던지 모두 허용한다는 의미를 갖고 있는 타입이다. 타입을 엄격하게 다루는 타입스크립트에서는 남용하면 타입스크립트 의미가 사라지지만, 자바스크립트로 구현되어 있는 웹 서비스 코드에 타입스크립트를 점진적으로 적용할 때 활용하면 좋은 타입이다.

◾ void

변수에는 undefinednull만 할당하고, 함수에는 반환 값을 설정할 수 없는 타입이다.

  const unUseful:void = undefined;
  const testFunc= (s : string):void => {
  	if(typeof s === string){
  	console.log('s is string')
  }
  }
  //반환값이 없는 함수의 return 타입을 지정할 때 사용한다.

✔ Typescript 특징

  • 정적타입의 Typescript

타입스크립트는 static script이다. 타입스크립을 컴파일 시켜 js로 변환시키면 타입이 다 빠져있고, es5 js로 변환된 것을 볼 수 있다.

이말은 즉슨, 개발도중에 끝나는 변수와 매개변수의 타입을 정의한다는 것을 의미한다.

자바스크립트 객체를 생성하는 것이 아닌, 작업 중인 객체를 타입스크립트가 이해 할수 있도록 해주는 객체타입의 하나인 타입스크립트의 표현 일 뿐이다.

✔ Typescript 강점

  • 타입을 정함으로써 , 강화된 함수와 코드를 만들 수 있음.

타입스크립트는 변수와 함수의 타입을 지정해서 코드를 작성하는데 도움을 준다. 이 타입을 이용해 조건문을 통해 다른 return을 가질 수 있도록 해주는 강점이 있다.

다음 포스팅은 심화된 Typescript에 대해서 포스팅 할 꺼임

profile
function = (Develope) => 'Hello World'

0개의 댓글