Literal Types을 쓰는 이유는 변수를 더 엄격하게 관리해서 오류를 방지하기 위해서 사용한다.
함수 입력값, 리턴값 등을 제한하는 용도로도 사용가능하다.
const 변수와 유사하게 사용가능하다.
//literal types 변수
let blog : 'tistory';
//'tistory'타입이기 때문에 tistory만 들어갈 수 있게 된다.
blog = 'tistory';
//에러 발생
blog = 123;
함수에 Literal Types 사용 예
//입력값으로는 Tistory, 리턴값으로는 true | false만 가능해진다.
function blog(a: 'Tistory') : true | false {
return true;
}
// 파워, 스피드, 테크닉 문자열로만 입력 리턴이 가능해진다.
function 공격 (a : "파워"|"스피드"|"테크닉") : ('파워' | '스피드' | "테크닉")[] {
return ['테크닉'];
}
Literal Types의 문제점
//Literal type의 문제점
var blog ={
name : 'tistory'
}
function Out_function(a: 'tistory') {
console.log(a);
}
Out_function("tistory") // "tistory" 출력
Out_function(blog.name) // 오류 발생
위 코드 처럼 Out_function 에는 'tistory'라는 문자열만 입력받을 수 있게 설정했다.
따라서 문법적으로는 blog.name에는 'tistory'라는 문자열이 담겨있어도 매개변수에 들어가면 그대로 입력을 받아버려서 오류가 발생한다는 문제점이 있다.
이 문제의 해결방법은 3가지가 있다. 1. object를 만들때 타입지정 확실히 하기 {name : 'tistory'} ) 2. as 문법 사용하기 as {name : 'tistory'} 3. as const 키워드 사용
as const를 사용하면 obejct value 값을 그대로 타입으로 지정하고 readonly 속성을 붙이기 때문에 name이라는 키 값의 value값을 읽기만 할 뿐 변경할 수는 없게된다.
//Literal type의 문제점
var blog ={
name : 'tistory'
} as const // 3. as const
function Out_function(a: 'tistory' ) {
console.log(a);
}
Out_function("tistory")
Out_function(blog.name as 'tistory') //2. as 'tistory'
const
TypeScript 에서는 const를 이용해서 변수를 작성하면 대입형식으로는 변수 내부 데이터를 변경할 수 없다.
즉, 등호로 재할당을 막게된다.
const blog = 'tistory';
//blog = 'velog'; 오류 발생
하지만 const로 object 자료를 사용하는 경우 수정이 가능하다.
const blog = {
name:'tistory'
}
blog.name = 'velog' // const 변수지만 error가 발생하지 않고 데이터가 수정된다..
이런 경우 수정을 막고싶다면 TypeScript의 readonly 속성을 사용하여 값을 읽기전용으로 만들어주면된다.
const blog = {
name:'tistory'
}
blog.name = 'velog' // const 변수지만 error가 발생하지 않고 데이터가 수정된다..