본문 바로가기

TYPESCRIPT

[타입스크립트] ReadOnly / Tuple / any

읽기 전용  ReadOnly

ReadOnly를 적용한 변수는 수정 및 추가, 변형 불가 (불변성)

type Age = number;
type Name = string;
type Student = {
	readonly name : Name
    // readonly : name을 수정하려고 한다면 오류 발생 
    age? :Age 
    }
    
const studnetMaker = (name :string) : Student => ({name})
const nico = studentMaker("woodi")
woodi.age =12

  Tuple

배열을 생성하게 하는데 최소한의 길이를 가져야 하고 특정 위치에 특정 타입이 있어야 함 

// 정해진 개수와 순서의 요소를 설정할 수 있음 
const string : [string , number , boolean] = ["woodi" , 1, ture ]
// 이 array가 최소 3개의 타입을 가지고, 위에 나열된 순서여야 함 

string[0] = 1
// 타입스크립트가 첫번째 인덱스는 항상 string이어야 함 
// 코드를 저장하고 실재 production 환경으로 보내기 전에 오류 확인 가능

// tuple에 readonly 추가
const string : readonly[string , number , boolean] = ["woodi" , 1, ture ]

 

any

타입스크립트로부터 빠져나오고 싶을 때(비활성화) 사용하는 값(아무 타입이나 가능)

비어있는 값을 사용하면 기본값이 any가 됨 

** 무분별한 any 사용을 막기 위한 규칙 > "가능한 사용하지 않을 것!!!"

const a : any[] = [1,2,3,4] 
const b : any = true 

a+b // 가능(any +any)

 

undefined / null

undetined : 선언하지도 않고 할당하지도 않음

null : 선언은 했지만, 할당하지 않은 값 

728x90