Typescript, Reactjs 교과서 읽으면서 헷갈리는 점 정리

nara_lee·2025년 2월 20일
0

Abstract class

추상 클래스(abstract class)는 하나 이상의 추상 메소드를 포함하며 일반 메소드도 포함할 수 있다. 추상 메소드는 내용이 없이 메소드 이름과 타입만이 선언된 메소드를 말하며 선언할 때 abstract 키워드를 사용한다. 추상 클래스를 정의할 때는 abstract 키워드를 사용하며, 직접 인스턴스를 생성할 수 없고 상속만을 위해 사용된다. 추상 클래스를 상속한 클래스는 추상 클래스의 추상 메소드를 반드시 구현하여야 한다.

abstract class Animal {
  // 추상 메소드
  abstract makeSound(): void;
  // 일반 메소드
  move(): void {
    console.log('roaming the earth...');
  }
}

// 직접 인스턴스를 생성할 수 없다.
// new Animal();
// error TS2511: Cannot create an instance of the abstract class 'Animal'.

class Dog extends Animal {
  // 추상 클래스를 상속한 클래스는 추상 클래스의 추상 메소드를 반드시 구현하여야 한다
  makeSound() {
    console.log('bowwow~~');
  }
}

const myDog = new Dog();
myDog.makeSound();
myDog.move();

interface

인터페이스는 일반적으로 타입 체크를 위해 사용되며 변수, 함수, 클래스에 사용할 수 있다. 인터페이스는 여러가지 타입을 갖는 프로퍼티로 이루어진 새로운 타입을 정의하는 것과 유사하다. 인터페이스에 선언된 프로퍼티 또는 메소드의 구현을 강제하여 일관성을 유지할 수 있도록 하는 것이다. ES6는 인터페이스를 지원하지 않지만 TypeScript는 인터페이스를 지원한다.

인터페이스는 프로퍼티와 메소드를 가질 수 있다는 점에서 클래스와 유사하나 직접 인스턴스를 생성할 수 없고 모든 메소드는 추상 메소드이다. 단, 추상 클래스의 추상 메소드와 달리 abstract 키워드를 사용하지 않는다.

꺾쇠 <> 기호를 변수명, 함수명 앞에다 쓰면 '타입 단언' 이 되게 된다.따라서 제네릭을 구현하려면 변수명, 함수명 뒤에다가 꺾쇠 괄호를 적어주어야 한다.그리고 제네릭명은 꼭 T가 아니어도 된다. 내마음대로 붙일수는 있지만 관습적으로 대문자 알파벳 한글자로 처리하는 편이다. (T, U, K ...)
출처: Inpa Dev:티스토리

import React, { ReactNode } from "react";

interface MyComponentProps {
  name?: string;
  age?: number;
  children?: ReactNode;
}

const MyComponent: React.FC<MyComponentProps> = ({
  name = "James",
  age = 0,
  children,
}) => {
  return (
    <div>
      Hello my name is {name} :P <br />
      My age is {age} <br />
      My children are {children}
    </div>
  );
};

export default MyComponent;

type FC<P = {}> = React.FunctionComponent


Represents the type of a function component. Can optionally receive a type argument that represents the props the component receives.

import React, { ReactNode, Component } from "react";

interface MyComponentProps {
  name?: string;
  age?: number;
  children: ReactNode;
}

class MyComponent extends Component<MyComponentProps> {
  static defaultProps = {
    name: "James",
    age: 0,
  };
  render() {
    return (
      <div>
        <h1>안녕하세요</h1>
        {this.props.children}
        <div>저는 {this.props.name} {this.props.age}살 입니다.</div>
      </div>
    );
  }
}

The static keyword allows react to get the values of propTypes and defaultProps, without initializing your component.
⚠️ defaultProps is deprecated⚠️

initial state 설정

import React, { Component } from "react";
  
// 옵션 1: constructor 쓰는 방법
class Counter extends Component {
  //   constructor(props) {
  //     super(props);
  //     this.state = {
  //       count: 0,
  //     };
  //   }
  
// 옵션 2: state keyword 쓰는 방법
  state = {
    count: 0,
  };
  
  render() {
    let { count } = this.state; //state 조회할 때는 무조건 this keyword 가 필요하다
    return (
      <div>
        <h1>{count}</h1>
        <button onClick={() => this.setState({ count: count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

export default Counter;

setState에 object 대신 function parameter 전달하기

기본 문법

this.setState((prevState, props) => {
  return {
  // 업데이트하고 싶은 내용
  }
})

0개의 댓글