1) 유니언 타입
유니언 타입 2개 이상의 타입을 허용하는 경우 유니언 타입이라고 함
| 타입구분 () 선택사항
ex)
let unionVar : (string | number) = 'green';
2) 인터섹션
인터섹션
&를 사용해 2개 이상의 타입을 조합하는 경우 인터섹션이라고 합니다.
ex)
interface IUser {
name: string,
name: string,
age: number
}
interface IValidation {
isValid: boolean
isValid: boolean
}
const neo: IUser & IValidation = {
name: "Neo",
age: 30,
isValid: true
}
3) 타입 추론
타입 추론
명시적으로 타입선언이 되어 있지 않은 경우, 타입스크립트는 타입을 추론해서 제공함.
1. 초기화된 변수
let num2 = 20 // number
2. 기본값이 설정된 매개 변수
function add(a: number, b=2) }
}
3. 반환 값이 있는 함수
function add(a: number, b=2) {
return a+b
return a+b
}
ex)
function addFunc(a: number, b=2) {
return a+b
return a+b
}
addFunc(10,'g'); // Error: number가 아니다.
let result: string = addFunc(10,20) // 반환값이 number이기 때문에 string으로 받을 수 없다.
4) 타입단언
타입단언
타입추론을 통해 판단할 수 있는 타입의 범주를 넘는 경우 더이상 추론하지 않도록 지시하는 것
function someFunc(val: string | number, isNumber: boolean){
if(isNumber) {
// 1. 변수 as 타입 (val as number)
// 2. <타입>변수 (<number>val)
(var as number).toFixed(2)
(<number>val).toFixed(2)
}
}
'개발이 좋아서 > TypeScript가 좋아서' 카테고리의 다른 글
react - Typescript_ContextAPI (0) | 2022.07.28 |
---|---|
react - Typescript_Generic (0) | 2022.07.26 |
react - Typescript_interface, keyof (0) | 2022.07.26 |
react - Typescript_Tuple, Enum (0) | 2022.07.26 |
react - Typescript (0) | 2022.07.25 |