개발 블로깅/TypeScript

[2019.07.13] React에 TypeScript를 적용하면 constructor를 쓰지 않는다?

Hello이뇽 2019. 7. 13. 19:34

 

 

클래스형 컴포넌트 안에서 state를 사용할 때, 일반적으로 아래와 같은 코드로 구현한다.

# React 클래스 컴포넌트에서 일반적인 state 선언 방식

class component extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      name: '',
      age: 0
    }
  }
  
  render()(
    <div>hello Typescript<div>
  )
}

 

여기서 타입스크립트를 적용시키면 변경되는 부분이 몇 군데 있다.

# React에 TypeScript를 적용시킬 시, 일반적인 클래스 컴포넌트 사용 방식

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

class component extends React.Component<State> {
  constructor(props){
    super(props);
    this.state = {
      name: '',
      age: 0
    }
  }
  
  render()(
    <div>hello Typescript<div>
  )
}

 

interface로 state로 사용할 데이터의 타입을 적용시킨다.

그리고 우리가 알고 있듯이, constructor 안에 super문과 this.state를 선언하여 해당 컴포넌트의 state 값을 생성한다.

 

그런데 여기서 재미있는 것은, 위 코드에서 두 줄을 없애고 state를 생성할 수 있다.

그 코드는 바로 아래와 같다.

# constructor, super문을 없애고 선언한 state 방식

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

class component extends React.Component<State> {
  state:State = {
      name: '',
      age: 0
    }
  
  render()(
    <div>hello Typescript<div>
  )
}

 

짠~!

state를 생성하기 위해, constructor, super 코드를 쓰는 것을 안 해도 된다~!

state를 해당 클래스의 속성 방식으로 사용하는 것이다. 

주의할 점은 꼭 state 속성 옆에 인터페이스를 명시해주어야 한다. 그래야만 constructor 안에서 state를 선언한 것과 같은 효과를 보인다고 한다.

 

# 참고내용

https://stackoverflow.com/questions/51465921/react-typescript-constructor-state-vs-property

 

react typescript constructor state vs property

I have following typescript code: interface Props extends WithStyles { } interface State { users: Array; } class UsersTable extends React.Component<props, s...<="" p=""> </props,>

stackoverflow.com


 

TypeScript 좋다...

자바스크립트 개발할 때는 뭔가 잘 안 돌아갈 것 같아서 무조건 중간중간에 돌려보면서 체크를 했었는데, 타입스크립트 덕분에 한 번에 개발을 쭈욱 하다가 실행해도 잘 되는 것 같다~!

 

TypeScript에 갈수록 매력에 빠지는 중...ㅎ

반응형