Typescript
[Typescript] 타입가드, interface, 확장, 타입별칭, 함수 오버로딩
furaha
2023. 9. 26. 15:42
반응형
타입가드의 예제
예제 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에 해당된다고 생각할 수 있지만 리턴값의 타입이 지정되지 않아서 해당되지 않음
반응형