function 함수(x : number | string) {
return x + 1 ; //error
(이유: union type에는 조작을 못하게 막아놓음)
//solution
function 함수 (x: number | string) {
if( typeof x === 'number) {
return x + 1
} else if( typeof x=== 'string') {
return x + 1
} else {
return 0
}
}
이렇게 타입을 파라미터로 검사해서 코드를 짜야 정상적으로 작동
단, 함수 안에서 if문을 쓸 때에는 마지막 else {}가 없으면 에러가 남
변수명 as string
function 함수 ( x: number | string) {
return (x as number) + 1
}
console.log(함수(123)) // 124
as 키워드의 특징
1. as 키워드는 union type 같은 복잡한 타입을 하나의 정확한 타입으로 줄이는 역할을 수행
2. 실제 코드 실행결과는 as 있을 때나 없을 때나 동일
as 문법 사용?
1. 임시로 에러해결
2. 컴파일러 에러가 날 때
type Animal = string | number | undefined;
let 동물 : Animal
type 타입변수명 = 타입종류
//object 타입
type 사람 = {
name: string,
age: number,
}
let teacher: 사람 = {name: '나현', age: 28}
const 출생지역 = 'seoul';
출생지역 = 'busan' // error
object 자료를 const에 집어넣어도 object 내부는 마음대로 변경가능
const 여친 = {
name: '나현'
}
여친.name = '이나현'; //error 안남
type GirlFriend = {
readonly name : string,
}
let 여친: GirlFriend = {
name: '나현'
}
여친.name = '이나현' //error
한번 부여된 후엔 앞으로 바뀌면 안될 속성들을 readonly로 잠궈버림
type Square = {
color? string,
width: number,
}
let 네모2 : Square = {
width: 100
}
물음표 연산자는 'undefined라는 타입도 가질 수 있다~'라는 뜻
type Name = string;
type Age = number;
type NewOne = Name | Age;// Union type