더보기에 있는 링크와 이어집니다.

스태틱&인스턴스

// 스테틱
class MyClass {
  static staticProperty = "I belong to the class!";
  static staticMethod() {
    console.log("This is a static method.");
  }
}

console.log(MyClass.staticProperty); 
MyClass.staticMethod(); // 스테틱 메서드

// 인스턴스
class MyClass2 {
  instanceProperty = "I belong to an instance!";
  instanceMethod() {
    console.log("This is an instance method.");
  }
}

const instance = new MyClass2();
console.log(instance.instanceProperty); 
instance.instanceMethod(); // 인스턴스 메서드

 

* 스테틱인스턴스의 차이

 

스테틱

  • 클래스 자체에 속한다.
  • 클래스 이름을 통해 직접 접근한다.
  • 인스턴스와 연관이 없다.

인스턴스

  • 클래스의 인스턴스를 통해 접근한다.
  • 인스턴스마다 고유의 값을 얻을 수 있다.

하이브리드 타입

나의 객체가 여러 형태를 가질 수 있도록 정의

interface Counter {
  (start: number): string; // 함수 시그니처
  interval: number;        // 속성
  reset(): void;           // 메서드
}

function getCounter(): Counter {
  const counter = ((start: number) => `Count starts from ${start}`) as Counter;
  counter.interval = 1000;
  counter.reset = () => {
    console.log("Counter reset!");
  };
  return counter;
}

const counter = getCounter();
console.log(counter(5));         // Count starts from 5
console.log(counter.interval);    // 1000
counter.reset();                  // Counter reset!

 

클래스 확장 인터페이스

클래스에서 상속한 필드와 메서드 타입을 인터페이스가 받아들여,
그 클래스의 구조를 기반으로 한 인터페이스를 정의할 수 있는 기능

 

class Animal1 {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  makeSound(): void {
    console.log(`${this.name} makes a sound.`);
  }
}

interface Pet extends Animal1 {
  owner: string;
  play(): void;
}

class Dog implements Pet {
  name: string;
  owner: string;

  constructor(name: string, owner: string) {
    this.name = name;
    this.owner = owner;
  }

  makeSound(): void {
    console.log(`${this.name} barks!`);
  }

  play(): void {
    console.log(`${this.name} is playing with ${this.owner}.`);
  }
}

// 사용 예시
const myDog = new Dog("Buddy", "Alice");
myDog.makeSound(); // Buddy barks!
myDog.play();      // Buddy is playing with Alice.

'TS' 카테고리의 다른 글

함수(Function)[2]  (0) 2024.11.25
함수(Function)[1]  (0) 2024.11.20
Interface (2)  (0) 2024.11.18
Interface (1)  (0) 2024.11.15
Interface  (0) 2024.11.08

Interface

객체가 어떤 속성과 메서드를 가져야 하는지 지정

 

interface labelValue {
    size: number;
    label: string;
}

function printLabel(labelObj: { label: labelValue }) {
    console.log(labelObj.label);
}

let myObj: labelValue = { size: 10, label: "size 10 object" }; // labelValue 타입으로 정의
printLabel({ label: myObj });

 

선택적 프로퍼티

객체 안에 몇 개의 프로퍼티만 채워 함수에 전달, 선언에서 프로퍼티 이름 끝에 ?를 붙여 표시

interface SquareConfig {
    color?: string; // 색상명
    width?: number; // 둘레 수치
}

function createSquare(config: SquareConfig): {color: string; area: number} {
    let newSquare = {color: "white", area: 100};
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({ color: "black" });
console.log(mySquare);

 

읽기 프로퍼티

할당 후 수정 불가인 속성, 앞에 readonly를 넣는다.

interface read{
    readonly x: string;
    readonly y: number;
}

let x1: read = { x: "number", y: 123 };
// x1.x = "apb"; // 오류
// x1.y = 5; // 오류
console.log(x1);

let a: number[] = [1, 2, 3, 4];
let arr: ReadonlyArray<number> = a;

console.log(arr);

 

초과 프로퍼티 검사

객체 리터럴이 특정 인터페이스나 타입에 할당될 때,

해당 객체에 타입에 정의되지 않은 초과 프로퍼티가 포함되어 있는지 검사하는 과정

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "Alice",
  age: 25,
  hobby: "reading", // 에러: 'hobby'는 User 타입에 정의되지 않음
};

User 인터페이스에는 name과 age만 정의되어 있으므로 hobby는 초과 프로퍼티로 간주되어 컴파일 오류를 발생

 

예외 처리 : 초과 프로퍼티 검사 무시 방법

// 1. 객체 리터럴을 변수에 먼저 할당하는 경우
const obj = { name: "Alice", age: 25, hobby: "reading" };
const user: User = obj; // 오류 없음

// 2. 인덱스 시그니처 사용
interface User {
  name: string;
  age: number;
  [key: string]: any; // 추가 프로퍼티 허용
}

const user: User = {
  name: "Alice",
  age: 25,
  hobby: "reading", // 오류 없음
};

// 3. 타입 단언
const user = {
  name: "Alice",
  age: 25,
  hobby: "reading",
} as User; // 오류 없음

// 4. 객체 확산 연산자 사용
const obj = { name: "Alice", age: 25, hobby: "reading" };
const user: User = { ...obj, hobby: undefined }; // hobby 제거

 

 

'TS' 카테고리의 다른 글

Interface(3)  (0) 2024.11.19
Interface (2)  (0) 2024.11.18
Interface  (0) 2024.11.08
TypeScript의 타입 (이전 글 추가)  (0) 2024.11.07
TypeScript의 타입  (0) 2024.11.05

Interface

interface 키워드를 사용하여 정의,

인터페이스는 선택적으로 읽기 전용 속성, 선택적 속성, 메서드를 가질 수 있다.

 

문법

interface User {
  name: string;          // 이름 (필수), 문자열 타입
  age: number;           // 나이 (필수), 숫자 타입
  email?: string;        // 이메일 (선택적 속성)
  readonly id: number;   // ID (읽기 전용)
}

 

예시

interface User {
  name: string;          // 이름 (필수)
  age: number;           // 나이 (필수)
  email?: string;        // 이메일 (선택적 속성)
  readonly id: number;   // ID (읽기 전용)
}

const user: User = {
  name: "John",
  age: 30,
  id: 1
};

// 읽기 전용 속성은 수정할 수 없음
user.id = 2; // 오류 발생

console.log(user);

콘솔창에 { name: 'John', age: 30, id: 2 } 출력

'TS' 카테고리의 다른 글

Interface (2)  (0) 2024.11.18
Interface (1)  (0) 2024.11.15
TypeScript의 타입 (이전 글 추가)  (0) 2024.11.07
TypeScript의 타입  (0) 2024.11.05
TypeScript란 무엇인가?  (0) 2024.11.04

+ Recent posts