- 인프런 강의 Part 5. TS
02-03. 타입 종류
// 혼합 배열 ( 혼합 type, 동시에 여러개의 타입을 지정하고 싶을 떄=> union 사용)
const union: (string|number)[] = ['Apple',1,2,'Banana',3]
// 객체
// typeof DATA === 'object'
const obj: object = {}
const arr: object = []
const func: object = function () {}
// 인터페이스: 이름을 지정하고 재사용이 가능한 별도의 객체타입
interface User {
name: string
age: number
inValid: boolean
}
// tuple : 배열과 비슷, 배열의 정확한 ele 개수& 순서까지 명시할 때
const tuple: [string,number, boolean] = ['a',1,false]
// void: return 키워드를 작성하지 않은 함수에서 반환되는 데이터의 타입
// Intersection (&연산자, type을 합칠 때 사용)
interface User {
name: string,
age: number
}
interface Validation {
inValid: boolean
}
const heropy: User & Validation = {
name: 'Neo',
age: 88,
inValid: true
}
04. 타입 추론 ( Inference)
타입스크립트는 기본적으로 타입 추론을 해준다.
'추론' : 어떠한 판단을 근거로 삼아 다른 판단을 이끌어 냄
근거:
1. 초기화된 변수
2. 기본값이 설정된 매개 변수
3. 반환 값이 있는 함수
// 초기화된 변수
let num = 12;
num = 'hello' // error
// 기본값이 지정된 매개 변수 & 반환 값이 확실한 함수 => 반환값의 타입인 number 생략 가능
function add(a: number, b = 2) {
return a+b
}
=> 결론. typescript가 제공하는 타입 추론을 활용하여 최대한 타입을 적게 꼭 필요한 곳에서만 적어서 가독성을 좋게 하자
05. 타입 및 할당 단언 (assertions)
'단언': 주저하지 아니하고 딱 잘라 말함
1. 단언 키워드 as
ex 1)
const el = document.querySelector('body') // 제공된 선택자로 요소를 찾지 못하면 null 데이터를 반환한다.
el.textContent = 'Hello world?!' //error: el의 type은 HTMLBodyElement | null
// 그치만 body 태그는 무조건 있으므로(null이 아니므로) 타입을 단언해 본다.
// 단언 키워드 as 를 사용한다.
const el = document.querySelector('body') as HTMLBodyElement // null 데이터를 반환하지 않음
el.textContent = 'Hello world?!' // 에러발생 X
ex 2) 잘못된 타입 단언
function getNumber(x: number | null | undefined){
return Number((x as Number).toFixed(2)) // toFixed 메서드는 number에만 사용가능하므로 number로 타입 단언을 해준다.
}
getNumber(null) // 타입 에러, 잘못된 타입 단언을 사용했기 때문, 코드상에서는 에러가 발생하지 않으나 동작시켰을 때 발생함
ex 3)
function getValue(x: string | number, isNumber: boolean) {
if(isNumber){
return Number((x as number).toFixed(2))
}
return (x as string).toUpperCase()
}
2. non-null 단원 연산자 !
: null 데이터가 아니다 라고 단언해줌
ex 1)
const el = document.querySelector('body')
el!.textContent = 'hello world!' // el 은 null 이 아니다
ex 2)
function getNumber(x: number | null | undefined){
return Number(x!.toFixed(2)) // x는 null 이나 undefined 가 아니다. ,, 근데 잘못된 코드
}
getNumber(null) // 왜냐면 여전히 매개변수에 null이 들어갈 수 있음,,
3. 타입 단언 하기 예시
ex 1)
const el = document.querySelector('.title') // 근데 title 태그가 없다면?
if (el) { // 조건문으로 단언문을 대체 = Type Guard
el.textContent - 'hello world'
}
ex 2)
function getNumber(x: number | null | undefined) {
if (x) { // Type Guard 사용
return Number(x.toFixed(2))
}
}
4. 할당 단언 (assertion)
변수에 할당이 된 것 처럼 단언해주는 것
let num: number
console.log(num) // error: 변수가 할당되기 전에 사용되었습니다
// 할당 단언 (! 사용)
let num!: number // 이 변수는 이미 할당 되었다(구라)
06. 타입 가드 (Guards)
if 조건 등을 통해 방어하는 코드
function logText(el: Element) {
console.log(el.textContent)
}
// 요소를 못찾으면 null이 반환되기 때문에 타입 단언을 해준다..
// 그치만 여전히 null이 될수 있으므로 잘못된 단언이다
const h1E1 = document.querySelector('h1') as HTMLHeadingElement (X)
logText(h1E1)
// 타입 가드 사용
const h1E1 = document.querySelector('h1')
if (h1E1) {
logText(h1E1)
}
if (h1E1 instanceof HTMLHeadingElement) { // null 인 경우 통과하지 못함
logText(h1E1)
}
// 타입 가드 또다른 예시
if (typeof val === 'number') ~~~
'Typescript' 카테고리의 다른 글
Typescript 기초 문법 3 (0) | 2024.05.25 |
---|---|
Typescript 기초 문법 - 인터페이스 (2) | 2024.05.09 |
type- record (0) | 2024.03.06 |
벨로퍼트 Typescript_ 인터페이스 (0) | 2023.09.07 |
벨로퍼트 Typescript 정리 (2) | 2023.08.25 |