Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- map
- Filter
- Firebase
- foreach
- 패스트캠퍼스 부트캠프
- 패스트캠퍼스
- react hook
- reduce
- 야놀자x패스트캠퍼스
- 프론트엔드부트캠프후기
- 프론트엔드개발자
- 부트캠프 취업후기
- 퍼블리셔 이직후기
- TypeScript
- 국비지원취업
- 성능개선
- git
- 야놀자 fe 1기
- js CRUD
- promise 비동기처리
- 2024 sqld
- sqld 자격증 시험
- 부트캠프
- 리액트오류
- css 꿀팁
- github
- firebase rules
- 국비지원
- sqld 55회
- Where
Archives
- Today
- Total
Tech is created to fix problem
[Typescript] 타입가드, interface, 확장, 타입별칭, 함수 오버로딩 본문
반응형
타입가드의 예제
예제 1
function logText(el: Element) {
console.log(el.textContent)
}
const h1El = document.querySelector('h1')
if (h1El instanceof HTMLHeadingElement) {
logText(h1El)
}
예제 2
function add(val: string | number) {
let res = `Result =>`
if (typeof val === 'number'){
res += val.toFixed(2)
} else {
res += val.toUpperCase()
}
console.log(res)
}
add(3.141592)
add('hello world')
타입가드란 에러가 발생할 수 있는 상황을 미연에 방지하고자 코드상에서 방어한다는 개념이다
Interface
interface User {
name: string
age: number
isValid: boolean
}
const neo: User = {
name: 'Neo',
age: 85,
isValid: true
}
읽기전용 속성은 readonly
interface User {
name: string
readonly age: number
isValid?: boolean
}
1) 함수타입
// 호출 시그니처 (함수 타입 지정)
interface GetName {
(message: string): string
}
// 매개변수와 반환값의 타입 지정
interface User {
name: string
age: number
getName: GetName
}
const heropy: User = {
name: 'Ann',
age: 85,
getName(message: string){
console.log(message)
return this.name
}
}
heropy.getName('Hello') --> GetName 형식에 호출 시그니처가 없다?!
왜 만들어야할까? 재사용성 때문에
2) 인덱스 가능 타입
- 배열 방식
// 호출 시그니처
interface Fruits {
[item: number]: string
// 키와 값
}
const fruits: Fruits = ['Apple', 'Banana', 'Cherry']
console.log(fruits)
- 객체 방식
interface User {
[key: string]: unknown
name: string
age: number
}
const heropy: User = {
name: 'Heropy',
age: 85
}
heropy['isValid'] = true
heropy['emails'] = ['thesecon@gmail.com', 'test@gmail.com']
console.log(heropy)
확장(상속)
interface UserA {
name: string
age: number
}
interface UserB extends UserA {
isValid: boolean
}
const heropy: UserA = {
name: 'Heropy',
age: 85,
isValid: true
}
const neo: UserB = {
name: 'Neo',
age: 102,
isValid: true
}
타입 별칭(별명)
type TypeA = string
type TypeB = string | number | boolean
type User = {
name: string
age: number
isValid: boolean
} | [string, number, boolean]
const userA: User = {
name: 'Neo',
age: 85,
isValid: true
}
const userB: User = ['Evan', 36, false]
union 이나 intersection 타입에 사용하기 유용함
함수 오버로딩
function add1(a: string, b: string){
return a + b
}
function add2(a: number, b: number){
return a + b
}
// 아래처럼 오버로딩으로 수정 가능
function add(a: string, b: string): string //타입 선언
function add(a: number, b: number): number //타입 선언
function add(a: any, b: any){ //함수 구현부
return a + b
}
add('hello', 'world') // 'hello world'
add(1, 2) // 3 // 3
add('hello', 2) --> 오류남 (매개변수 두개가 string이거나 number이어야함)
--> 3번째 add에 해당된다고 생각할 수 있지만 리턴값의 타입이 지정되지 않아서 해당되지 않음
반응형
'Typescript' 카테고리의 다른 글
[Typescript] 클래스와 접근제어자, 제네릭, tsconfig.json 구성 옵션 (0) | 2023.09.26 |
---|---|
[Typescript] 추론, 단언, 할당단언 (0) | 2023.09.26 |
[Typescript 기본개념] JS보다 타입이 더 많은 TS (0) | 2023.08.30 |