<< 타입 정의 >>
[ 정의 방식 ]
- var : 이제 안 씀
- let : 이걸로 변수 정의
- const : 상수 변수 정의
< Type 종류 >
[ 원시 타입 ]
- string
- number
- boolean
- ex. let age: number = 36
[ 배열 ]
const 변수명: string[]= []
array.push('') // 변수 타입과 같은 원소
const 변수명: (string|number)[] = ['d', 1] // Union
let book__name_price:[string, number] = ['카밍 시그널', 13320]; // tuple
- Union : 여러 타입 넣기 가능
- Tuple (https://yamoo9.gitbook.io/typescript/types/tuple)
[ 객체 타입 ]
- Key-Value (https://yamoo9.gitbook.io/typescript/types/object)
const user: {name: string; age: number} = {
name: 'Hana',
age: 36
}
// -> user.name
// ### Optional 속성 ###
function printName(obj: { firstName: string, lastName?: string }) {...}
printName({firstName: 'Hana'}) // 가능 (인수 생략 가능)
printName({firstName: 'Hana', lastName: 'Kim})
[ any ]
- 모든 타입 다 가능
[ 함수 ]
function(인수_1: 타입_1, 인수_2: 타입_2 ...): 반환타입 {
return 'Hello ${인수_1}'
}
// 인수에 옵셔널 사용 가능
(..., 인수_2?: 타입_2)
// 인수 기본값 지정 가능
(..., 인수_3: 타입_3 = '...')
// 인수를 함수로(!!) 받을 수 있음
function func1(..., formatter: (인수_2:string) => string ) {
console.log(formatter(인수_1))
}
function formatFunc(name: string): string { return '${name} 씨'}
func1('홍길동', formatFunc) // -> 홍길동씨
< 기본 Type 기능 >
[ Type Annotation ]
-> as
이 변수는 이 타입으로 가져와야 한다~ 이 말이야
// 변수 = 값 as 타입
const myCanvas = document.getElementById('main_canvas') as HTMLElement
// 이걸 좀 더 유하게
const res = (response as any) as User
[ Type Alias ]
-> 타입 별명 짓기
코드 가독성 굿
미리 타입 지정해주어요
대문자로 스타트 하는 듯 해요
type 타입명 = 값
/////// ex 1 : 단순
type Name = string
////// ex 2 : 속성 ㅇ
type Point = {
x: number;
y: number;
}
function printPoint(point: Point) {
//point.x, point.y
}
printPoint({ x: 100, y: 100 })
// 인수 속성명 동일해야 함
////// ex 3 : 함수
type Formatter = (a: string) => string
function printName(name: string, formatter: Formatter) {
// formatter(name)
}
////// ex 4 : 객체 K-V 명시 X
type Label = {
[key: string] : string
}
const labels: Label {
topTile: '제목입니다.', ...
}
[ Interface ]
Type AS 와 비슷
하지만! 확장성 높음
interface Point {
x: number;
y: number;
}
// 나중에 이런 식으로 속성 추가 가능
interface Point {
z: number;
}
// Implements 도 된다고 해요
class MyPoint implements Point {
x: number;
y: number;
z: number;
}
// extends도 된다고 해여
interface Circle {
radius: number;
}
interface CirclePoint extends Point, Circle {}
[ Class ]
Class도 된대요
어디까지 되는 걸까요?
완전 객체지향언어 같애요
class Point {
x: number; // 필드에 접근 수정자(public 등) 부여 가능
// 우와 생성자도 도ㅑ요 짱이다 -생성자는 초깃값 지정해주는 친구예요
constructor(x: number = 0) {
this.x = x
}
// void 함수
moveX(n: number): void {
this.x += n
}
}
const point = new Point()
point.moveX(10) // -> x 값 : 10
< 실제 개발 시 중요 타입 >
- Enum : C#을 하셨다면 아시겠죠 우리의 열거형 친구입니다.
- Generic : 타입 추상화 -> 외부에서 구체적 타입 지정
- e.x. `class Queue<T> {} -> const queue = new Queue<number>()`
- 합집합(Union), 교집합(Intersection)
- 이미 나온 내용이랑 대충 비슷
- Literal : 정해진 걸로 이용 가능
- e.x. `let status: -1 | 0 | 1`
- never : 절대! 발생 X 반환 -> 에러 체크 함수에 사용
- 활용 예 : switch-case 문의 default 가 안 나오는 게 정상일 때가 있자나요? 그를 때 씁니다
switch (type) {
...
default: // 여기로 오면 안 됨
const wrong: never = type
throw new Error('${wrong} is not in Types')
}
'Programming > Web' 카테고리의 다른 글
Next.js 빌드 자동화 (0) | 2024.06.21 |
---|---|
React Next.js 기초 튜토리얼 (+Node.js), 세팅을 마쳤으니 개발을 시작하지 _실전 웹 애플리케이션 개발 (4) (0) | 2024.04.16 |
React VSCode 세팅 & TyepScript 개발 도구 세팅(Prettier, ESLint, tsconfig.json)_실전 웹 애플리케이션 개발 (3) (0) | 2024.04.11 |
제로부터 시작하는 TypeScript VSCode 세팅_실전 웹 애플리케이션 개발 (2-1) (0) | 2024.04.10 |
Node.js, React, Next.js, TypeScript.. 그게 뭔데 개발자야_실전 웹 애플리케이션 개발 (1) javascript 차이점 (1) | 2024.04.09 |