//typescript의 readonly를 쓰면 object 자료 수정도 막을 수 있다.
// type Alias
type NameType = {
readonly name: string;
}
type AgeType = {
//Type 내 중복된 프로퍼티가 있어도, 에러가 발생하지 않는다.
readonly name: string;
// 프로퍼티 키에 ?(옵셔널)을 붙여서, 선택사항이라는 것을 타입스크립트에게 알려줄 수 있다.
age? : number;
}
// & 연산자로 object type Extend 하기.
type UnionType = NameType&AgeType
//type Alias를 조합하여 Union Type Alias로 만들 수 있다
const who:UnionType = {
name : 'myungseong'
}
// typescript의 에러는 에디터&터미널에서만 존재한다. readonly로 객체 프로퍼티 수정을 불가능하게 함.
// who.name = 'seonbin'
// type 만들고 적용하기
type CssStyleType = {
color? : string;
size : number;
readonly position: number[]
}
const box:CssStyleType = {
color: 'rgb(5,5,55)',
size: 1,
position: [3,5,2]
}
// type 만들고 적용하기
type userInfo = {
name : string;
phone: number;
email: string;
}
const user:userInfo = {
name: 'Kim',
phone: +'01044565234',
email: 'kimnbn@naver.com'
}
// type 만들고 적용하기
type AdultuserInfoType = {
name: string;
phone: number;
email: string;
isAdult: boolean;
}
const AdultUser:AdultuserInfoType = {
name : 'kim',
phone: +'01012345678',
email: 'kwewdf@naver.com',
isAdult: true
}
// 더 엄격한 타입 지정도 가능하다. Literal Types
let myName:'kim'|boolean = 'kim';
myName = 'kim'
//함수의 리턴 값의 타입도 엄격히 정의할 수 있다.
function returnOne(a:1): number{
return a * 4995;
}
// 인자에는 rock,scissors,paper만 들어올 수 있고, 최소한 비기는 수를 문자열로 이루어진 배열로 반환해야 한다.
function rsp(weapon:'rock'|'scissors'|'paper'):void{
const atleastDraw:string[] = [];
if(weapon === 'rock'){
atleastDraw.push(weapon,'paper')
}
if(weapon === 'scissors'){
atleastDraw.push(weapon,'rock')
}
if(weapon === 'paper'){
atleastDraw.push(weapon,'scissors')
}
console.log(atleastDraw)
}
rsp('scissors');
// Literal type의 문제점
const data = {
name : 'kim'
}
// params kim이라는 자료가 들어온다고 한게 아니라, kim이라는 type이 들어와야 하기에 Error가 난다.
function myFunc(params:'kim'){
return params
}
// Argument of type 'string' is not assignable to parameter of type '"kim"'.
myFunc(data.name)
//해결할 수 있는 방법.
// Assersion 문법 활용
myFunc(data.name as 'kim')
// object에 as const 키워드 활용
// object value 값을 그대로 타입으로 지정해준다.
// object 속성들에 모두 readonly를 부여한다.
const data = {
name: 'kim'
} as const