타입 추론 이란 컴파일러가 자동으로 변수, 표현식 등의 타입을 결정하는 프로세스let myNumber = 5; // [ number ] 로 타입 추론
let myString = "Hello"; // [ string ] 으로 타입 추론
let myBool = true; // [ boolean ] 으로 타입 추론
// ⭕️
myNumber = 23
myString = "Hi"
myBool = false
// ❌ 오류 : 변수 선언 시 타입 추론한 type과 다른 type으로 재할당 불가
myNumber = "15"
myString = true
myBool = 3
// CASE 1
function add(x: number, y: number) {
return x + y
}
const m = add (10, 5); // "m" 은 [ number ] 로 타입 추론
// CASE 2
function add1(x: number, y: number) {
return `${x}${y}`
}
const n = add1(10, 5); // "n"은 [ string ] 으로 타입 추론
let nums = [1, 2, 3, 4] // "nums" 는 [ number ] 로 타입 추론
let user = {
name: 'Eli', // "name" 는 [ string ] 으로 타입 추론
age: 30 // "age" 는 [ number ] 로 타입 추론
}
// ❌ 오류 : 배열 및 객체 선언 시 타입 추론한 type과 다른 type으로 재할당 및 추가 불가
nums.push('hello')
user.age = "30"
let mixesValue = [1, 2, 3, 'red', 'green', 'blue'] // "mixesValue" 는 [ string | number ] 로 유니온 타입 추론
표현식 as 지정할 타입const someValue: unknown = "Hey there"; // "someValue" 는 [ unknown ] 으로 타입 지정
// ❌ 오류 : 타입 지정을 [ unknown ] 으로 하였기 때문에 [ string ] 관련 메소드 사용 불가
const len = someValue.length
// ⭕️ as 를 사용하여 "someValue" 라는 변수에 [ string ] 이라는 타입 지정 후 [ string ] 관련 메소드 사용
const len1 = (someValue as string).length
// CASE 1 :
// "button" 은 [ HTMLElement | null ] 으로 타입 추론
const button = document.getElementById("button");
// ❌ 오류 : "disabled" 은 버튼에만 사용 가능한 메소드 이며 button은 버튼타입으로 명확히 지정해주지 않아서 오류 발생
button.disabled = false;
// ⭕️ [ as HTMLButtonElement ] 로 지정 해주면 버튼 메소드인 "disabled" 사용 가능
const button1 = document.getElementById("button") as HTMLButtonElement;
button1.disabled = false;
// 💡 하지만 "button1" 은 [ HTMLButtonElement | null ] 으로 유니언 타입 지정이 되어 있기 때문에,
// 해당 값이 존재하는 지 확인차 조건문(if) 사용 권장
// 조건문 ( 1 )
if(button2 instanceof HTMLButtonElement) {
button2.disabled = false;
}
// 조건문 ( 2 )
if (button2){
button2.disabled = false;
}
클래스 는 객체를 생성하기 위한 하나의 청사진/템플릿 역할을 한다
즉, 객체를 만들기 위한 설계도
ES6에서 도입된 클래스 문법 기반
생성자, 속성, 메서드로 구성
public : 외부에서 접근 가능 (기본 설정)
private / # (해시 이름) : 해당 클래스 내부에서만 접근 가능 , ES6 부터는 # 으로 대신하여 사용 가능
private 대신 # 사용 시 ...
📁 [tsconfig 파일 ] 수정 필요 → target 프로퍼티 값을 [ ES2015 이상 또는 ES6 ] 로 명시를 해주어야 함
protected : 해당 클래스 내부 및 서브 클래스에서 접근 가능
class Country {
name: string;
capital: string;
}
let country = new Country()
country.name = "South Korea"
country.capital = "Seoul"
console.log(country); // Country { name: 'South Korea', capital: 'Seoul' }
countryclass Country1 {
name: string;
capital: string;
// 객체가 생성될 때 실행되는 함수 (초기값 설정)
constructor (name: string, capital: string) {
this.name = name;
this.capital = capital;
}
}
// 자동으로 constructor 함수를 호출하여 속성 값을 바로 할당 가능
let country1 = new Country1("South Korea", "Seoul");
console.log(country1); // Country1 { name: 'South Korea', capital: 'Seoul' }
class Continent {
continentName: string;
constructor (name: string){
this.continentName = name;
}
getContinentName() {
return this.continentName;
}
}
class Country2 extends Continent{
name: string;
capital: string;
constructor (continentName: string, name: string, capital: string) {
super(continentName)
this.name = name;
this.capital = capital;
}
}
let country2 = new Country2('Asia', "South Korea", "Seoul");
console.log(country2); // Country2 { continentName: 'Asia', name: 'South Korea', capital: 'Seoul' }
extends Continent : Country2(자식) 는 Continent(부모) 클래스를 확장해서 상속받는다는 뜻super() 는 부모 클래스의 constructor(생성자) 를 호출하는 함수class Continent1 {
continentName: string;
constructor (name: string){
this.continentName = name;
}
getContinentName() {
return this.continentName;
}
}
class Country3 extends Continent1{
name: string;
capital: string;
constructor (continentName: string, name: string, capital: string) {
super(continentName)
this.name = name;
this.capital = capital;
}
getInfo() {
// 🔮 메서드 사용
return `${this.name}, ${this.capital}, ${this.getContinentName()}`
}
}
let country3 = new Country3('Asia', "South Korea", "Seoul");
console. log(country3.getInfo()); // South Korea, Seoul, Asia
this.getContinentName() 이거 대신 this.continentName 으로 사용 가능하지만 최대한 코드가 많아지고 복잡해질수록 속성에 직접 접근하는 것보다 함수로 관리class Continent2 {
// 📍 continentName 속성을 private 접근 제어자를 사용하여 제어
#continentName: string;
constructor (name: string){
// 내부 클래스 모든 private 속성에 # 추가 필수
this.#continentName = name;
}
getContinentName() {
return this.#continentName;
}
}
class Country4 extends Continent2{
name: string;
capital: string;
constructor (continentName: string, name: string, capital: string) {
super(continentName)
this.name = name;
this.capital = capital;
}
getInfo() {
// 🔮 접근 제어자별 사용 가능여부
return `${this.name}, ${this.capital}, ${this.getContinentName()}`
}
}
let country4 = new Country4('Asia', "South Korea", "Seoul");
console. log(country4.getInfo());
// 🔮 접근 가능여부
country4.#contientName
🔮 접근 제어자별 사용 가능여부
[private] : private continentName 으로 설정되었을 경우에는 여기서 this.getContinentName() 이 메서드를 통해서만 접근 가능
[protected] : protected continentName 으로 설정되었을 경우에는 여기서 this.continentName 속성도 직접 접근 가능 → 하위 클래스이기 때문
🔮 접근 가능여부
[private] : 접근 불가능 → 클래스 내부에서만 속성 직접 접근 가능
[protected] : 접근 불가능 → 클래스 내부 및 하위 클래스까지만 속성 직접 접근 가능
interface ContinentInterface {
// 📍 메서드 직접 정의 :
// 해당 인터페이스를 사용하는 클래스 Continent3 에서 속성인 continentName 가 private 이기 때문에 메서드로 직접 정의 !
getContinentName() : string;
}
interface CountryInterface {
capital: string;
getInfo(): string;
}
class Continent3 implements ContinentInterface{
#continentName: string;
constructor (name: string){
this.#continentName = name;
}
getContinentName() {
return this.#continentName;
}
}
class Country5 extends Continent3 implements CountryInterface {
#name: string;
capital: string;
constructor (continentName: string, name: string, capital: string) {
super(continentName)
this.#name = name;
this.capital = capital;
}
getInfo() {
return `${this.#name}, ${this.capital}, ${this.getContinentName()}`
}
}
let country5 = new Country5('Asia', "South Korea", "Seoul");
console. log(country5.getInfo());
interface : 이 인터페이스를 따르는 클래스나 객체는 반드시 이런 구조를 가져야 함을 명시해주는 틀
인터페이스는 외부에서 볼 수 있는 것(public)만 약속 / private이나 protected 멤버는 인터페이스에 안 넣는 게 원칙
상속과 인터페이스 적용 순서 : 확장 키워드 먼저 상속(extends) 시켜주고 , 인터페이스(implements) 적용 해주기
추상 class란 ?
“설계도”만 있고, 구체적인 내용은 자식 클래스가 완성하도록 강제하는 클래스! 즉, “뼈대만 정하고, 세부는 알아서 채워라!” 라는 느낌
abstract class AbstractCountry {
name: string;
capital: string;
constructor (name: string, capital: string) {
this.name = name;
this.capital = capital;
}
setup(): void {
console. log("setup complete")
}
// 📍 시그니처만 존재
abstract displayInfo(): void;
}
// 📍 클래스 생성 후 인스턴스화
class MyCountry extends AbstractCountry {
// 📍 상속받는 서브 클래스
displayInfo() {
console.log("display info called");
}
}
const myCountry = new MyCountry ("Germany", "Berlin");
myCountry.setup(); // setup complete
myCountry.displayInfo(); // display info called
abstract class : 추상 클래스 내부에 [ abstract ] 키워드가 사용된 멤버는 자식 클래스에서 반드시 이 메서드를 구현해야 함.
추상 클래스 내부에서는 시그니처만 정의 해주면 된다 / 구현 X → 시그니처만 존재.
추상 class는 아래처럼 바로 인스턴스화 시키는 게 불가능하다 → 새로운 클래스를 만들어 주어야 한다
let country = new Country
상속받는 서브 클래스에서 abstract 멤버[ displayInfo() ]에 대한 필수적으로 구체적인 구현,
[ setup() ]은 구현 안 해도 됨 → 부모 클래스에 완성된 함수
: 타입 자리에 대체될 타입을 나타내는 변수.
제네릭 함수, 클래스등 정의할 때 지정되며, 실제 사용 시에 구체적인 타입으로 대체된다.
// 범용적으로 “Type” 또는 “T”를 사용하지만 어떤 이름을 사용하여도 상관없다
function 함수_이름<Type>(arg: Type): Type { }
function genericFunction<T>(arg: T): T {
// 우리가 전달하는 타입에 맞춰서 반환 값이 결정된다
return arg;
}
interface GenericInterface<T> {
}
class GenericClass<T> {
}
let numbers: Array<number> = [1,2,3, 4,5] // "numbers" 의 타입은 [ number ] 임을 지정
let strings: Array<string> = ["1", "2", "3", "4"] // "strings" 의 타입은 [ string ] 임을 지정
// ⭕️ [타입지정]
let div = document.querySelector<HTMLDivElement>("#myDiv1");
let button = document.querySelector<HTMLButtonElement>("#myButton1");
// "button" 은 [ HTMLButtonElement | null ] 이라는 유니언 타입
// ? : button이 존재한다면, 즉 null이 아니라면 click()을 호출 / null 또는 undefined면 에러없이 undefined 반환
button?.click();
// ❌ [타입 미지정]
// "button1" 은 [ Element | null ] 이라는 유니언 타입
// 타입 지정을 명확히 해주지 않으면 이 버튼이 가지고 있는 속성이나 메서드에 접근할 수 없음
let button1 = document.querySelector("#myButton2");
button1?.click();
let numbers: Array<number> = [1, 2, 3, 4, 5]
let strings: Array<string> = ["1", "2", "3", "4"]
// 🟢 [ 제네릭 미사용 코드 ]
function getFirstElement(arr: number[]) {
if(!arr.length){
return undefined;
}
return arr[0];
}
function getFirstStringElement(arr: string[]) {
if(!arr.length){
return undefined;
}
return arr[0];
}
const firstNumber = getFirstElement(numbers);
const firstString = getFirstStringElement(strings);
// 🟢 [ 제네릭 사용 코드 ]
function getFirstElement1<T>(arr: T[]): T | undefined {
if(!arr.length){
return undefined;
}
return arr[0];
}
// 같은 함수로 두 개의 타입 구현 가능
const firstNumber1 = getFirstElement1(numbers);
const firstString1 = getFirstElement1(strings);
<T>는 “제네릭 타입” 선언 / T 는 타입의 변수 (Type Variable)// 🟢 [ 제네릭 미사용 코드 ]
interface strDict {
[key: string]: string;
}
let strobj: strDict = {
name: "Elliot",
}
interface numDict {
[key: string]: number;
}
let numObj: numDict = {
age: 30,
};
// ----------------------------------------------------------------------------------------
// 🟢 [ 제네릭 사용 ]
// [ 한 개의 타입 ]
interface Dict<T> {
// []로 감싼 건 “여러 개의 키를 허용하는 객체”를 의미하는 문법
[key: string]: T
}
let strobj1: Dict<string> = {
name: "Elliot",
hobby: "soccer"
}
let numObj1: Dict<number> = {
age: 30,
};
// [ 두 개 이상의 타입 ]
interface Entry<K, V> {
key: K;
value: V;
}
let entry: Entry<string, number> = {
key: "age",
value: 25
}
let entry2: Entry<number, string[]> = {
key: 1,
value: ["red" , "green" , 'Blue']
}
class Item<T> {
#content: T | null;
constructor() {
this.#content = null
}
// setItem 호출시 받아오는 값이 T로 타입을 받아올 수 있도록
setItem(value: T){
this.#content = value;
}
// 이 함수 호출 시 매개변수로 받아오는 값이 없고, 반환값만 있음
// 반환 값은 T 로 정의된 타입 혹은 null 로 설정
getItem(): T | null{
return this.#content
}
}
const numberItem = new Item<number>()
numberItem.setItem(100)
numberItem.getItem() // 100 반환
const stringItem = new Item<string>()
stringItem.setItem("hello")
stringItem.getItem() // hello 반환
// [ 1 ]
interface User {
id: number;
name: string;
}
interface WithId {
id: number;
}
// 🔮 제네릭에 제약 추가
interface Store<T extends WithId> {
// save : 저장만 하기 때문에 리턴값 필요 X
save(item: T): void;
findById(id: number): T | undefined;
}
class UserRepository implements Store<User> {
// 🔮 private 필드 : 유저 데이터를 안전하게 내부에 저장할 목적으로 만든 비공개 저장소
#users:User[] = [];
findById(id: number) : User | undefined {
return this.#users.find(user => user.id === id);
}
// save 함수를 호출하여 데이터를 매개변수로 전달할 때 User 타입의 데이터만 받을 수 있는 함수
save(user: User): void {
this.#users.push(user);
}
}
const repo = new UserRepository();
repo.save({ id: 1, name: "Alice" });
repo.save({ id: 2, name: "Bob" });
console.log(repo.findById(1)); // { id: 1, name: 'Alice' }
console.log(repo.findById(3)); // undefined
// [ 2 ]
interface Product {
id: number;
price: number;
name: string;
}
class ProductRepository implements Store<Product> {
#product: Product[] = [];
findById(id: number): Product | undefined {
return this.#product.find(product => product.id === id)
}
save(product: Product): void {
this.#product.push(product)
}
}
const productRepo = new ProductRepository()
productRepo.save({ id: 10, price: 100, name: "Mouse"})
productRepo.findById(10)
// 제네릭 클래스 (큐 방식으로 동작하는 클래스)
// 큐: 선형 자료구조, FIFO (First-In-First-Out)
class GenericQueue<T> {
private items: T[] = [];
// enqueue 메서드 (큐에 데이터 추가)
enqueue(item: T): void {
this.items.push(item);
}
// dequeue 메서드 (큐의 맨 처음 데이터를 제거)
dequeue(): T | undefined {
return this.items.shift();
}
// peek 메서드 (큐의 맨 처음 데이터를 확인)
peek(): T | undefined {
return this.items[0];
}
// size 메서드 (현재 큐의 크기 반환)
size(): number {
return this.items.length;
}
}
// 테스트
const stringQ = new GenericQueue<string>();
stringQ.enqueue("Hello");
console.log(stringQ.peek()); // Hello
stringQ.dequeue(); // "Hello" 제거
stringQ.enqueue("TypeScript");
console.log(stringQ.size()); // 1
console.log(stringQ.peek()); // TypeScript