0%

210219_TIL(TypeScript)

오늘 배운 것

TypeScript

타입 변환 방법, 변수 선언식에도 타입을 지정하기 보다는 값에 대한 타입으로 변수 타입 추론을 활용하는 것이 좋다.

1
2
3
4
5
const $foo = document.querySelector("input[text]") as HTMLInputElement;
const val = $foo.value;

const $bar = <HTMLInputElement>document.querySelector("input[text]");
const va = $bar.value;

앨리어스와 interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 앨리어스
type TodoType = {
id: number;
content: string;
completed: boolean;
};

// 인터페이스
interface Todo {
id: number;
content: string;
completed: boolean;
}

const todos: Todo[] = [{ id: 1, content: "HTML", completed: false }];

const addTodo = (todo: Todo) => {
todos = [...todos, todo];
};

앨리어스와 interface 모두 객체에 대한 타입이기 때문에 파스칼 케이스를 사용한다.

interface의 경우 implements를 사용할 수 있다.

인터페이스의 프로퍼티가 선택적으로 필요한 경우 선택적 프로퍼티(Optional Property)는 프로퍼티명 뒤에 ?를 붙이며 생략하여도 에러가 발생하지 않는다.

1
2
3
4
5
6
7
8
9
10
11
interface UserInfo {
username: string;
password: string;
age?: number;
address?: string;
}

const userInfo: UserInfo = {
username: "ungmo2@gmail.com",
password: "123456",
};

제네릭

같은 형식에서 타입만 달라질 경우 반복되는 코드를 짜기보다는 제네릭을 활용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
// 인터페이스
interface Todo {
id: number;
content: string;
completed: boolean;
}

// 제네릭 형식
const todos: Array<Todo> = [{ id: 1, content: "HTML", completed: false }];

const addTodo = (todo: Todo) => {
todos = [...todos, todo];
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Queue<T> {
protected data: Array<T> = [];
push(item: T) {
this.data.push(item);
}
pop(): T | undefined {
return this.data.shift();
}
}

// number 전용 Queue
const numberQueue = new Queue<number>();

// string 전용 Queue
const stringQueue = new Queue<string>();

// 커스텀 객체 전용 Queue
const myQueue = new Queue<{ name: string; age: number }>();

Nyong’s GitHub