1)
// 유니언 타입 2개 이상의 타입을 허용하는 경우 유니언 타입이라고 함
// | 타입구분 () 선택사항
let unionVar : (string | number) = 'green';
// 인터섹션
// &를 사용해 2개 이상의 타입을 조합하는 경우 인터섹션이라고 합니다.
interface IUser {
name: string,
age: number
}
interface IValidation {
isValid: boolean
}
const neo: IUser & IValidation = {
name: "Neo",
age: 30,
isValid: true
}
// 타입 추론
// 명시적으로 타입선언이 되어 있지 않은 경우, 타입스크립트는 타입을 추론해서 제공함.
// 1) 초기화된 변수 let num2 = 20 // number
// 2) 기본값이 설정된 매개 변수
// function add(a: number, b=2) {
//
// }
// 3) 반환값이 있는 함수
// function add(a: number, b=2) {
// return a+b
// }
let num = 20;
function addFunc(a: number, b=2){
return a+b
}
// addFunc(10,'g'); // Error: number가 아니다.
// let result: string = addFunc(10,20) // 반환 값이 number이기 때문에 string으로 받을 수 없다.
// 타입단언
function someFunc(val: string | number, isNumber: boolean){
if(isNumber) {
// 1. 변수 as 타입 (val as number)
// 2. <타입>변수 (<number>val)
(val as number).toFixed(2)
// (<number>val).toFixed(2)
}
}
'노력이 좋아서' 카테고리의 다른 글
<step88>'react_typescript_interface, keyof, Generic' (0) | 2022.07.26 |
---|---|
<step88>'react_typescript_interface, keyof, Generic' (0) | 2022.07.26 |
<step88>'react_typescript_Tuple, Enum' (0) | 2022.07.26 |
<step87>'react_typescript' (0) | 2022.07.25 |
<step86>'redux(react)_프로젝트_마무리' (0) | 2022.07.22 |