본문 바로가기

Web_Study/TypeScript

TypeScript_2:Types

▶ TypeScript는 변수를 생성할때 Type을 지정이 필수는 아님

let a : number = 3
let b = 3 // type을 지정하지 않아도 typescript가 추론해서 type을 number로 지정

Basic Types

let a : number =1
let b : string = "Hi"
let c : boolean = true
led d : number[] = [1,2,3] // 숫자형 배열

Syntax 

변수명 : type = value

 

Optional Type

const player = {
	name:string,
    age?:number		// ?붙임으로써 age는 optional ( 있어도 Okay, 없어도 Okay )
   }={
   name="yjh"
  }

TypeScript는 age가 optional이기 때문에, 아래와 같은 보호장치 역할을 해줌.

// 오류 발생
if(player.age<10){
}

// 정상시행
if(player.age && player.age<10){
}

같은 형식의 type을 생성할 경우 Type을 생성할 수 있음

type Player = {
	name:string,
    age?:number
}

const playerA:Player={
	name:"Alice"
}

const playerB:Player={
	name:"Bob",
    age:14
 }

'Web_Study > TypeScript' 카테고리의 다른 글

TypeScript_6:Generic_2  (0) 2022.06.02
TypeScript_5:Polymorphism & Generic  (0) 2022.05.31
TypeScript_4:CallSignature & Overloading  (0) 2022.05.26
TypeScript_3:Types_2  (0) 2022.05.25
TypeScript_1 : Why use TypeScript?  (0) 2022.05.22