Frontend/React

(1) TypeScript

creativeDeveloper! 2023. 1. 13. 12:00
728x90

# Typescript?

 - js를 기반으로 한 프로그래밍 언어로 js와 거의 똑같은데 거기에 새로운 기능만 살짝 추가했다

- strongly-typed한 언어로 프로그래밍 언어가 작동하기전에 type을 확인한다.

예를 들어 원래 js문법은 

const plus = ( a,b ) => a+b; 

이렇게만 해주어도 오류가 나지 않는다.

타입스크립트를 사용하면

const plus = ( a:number , b:number ) => a+b;

이렇게 a와 b뒤에 숫자라고 타입까지 명명해줘야한다.

 

# 필요성

const user = {

firstName: "minJi"

lastName: "Kim" 

};

console.log(user.name);

콘솔에 출력했을때, js 는 사용자에게 undefined라고 보여줄 것이다.

왜냐면 user.name은 존재하지 않기 때문이다. 하지만 사용자에게 저대로 보여준다고해서

js의 잘못은 없다. 왜냐면 js는 원래 데이터타입을 신경쓰지 않는 애이기 때문에 자기할일을 한것이다.

 

하지만 타입스크립트를 사용하면 에러가 떠서 사용자에게 보여지기전에 방지할수있다.

개발자에게 user.name이 아니라 user.firstName , user.lastName이야 라고 알려줄것이다.

그게 우리가 타입스크립트를 사용하는 이유이다. 

다시말해 js가 하지 못하는 protection을 해줄 수 있다.

 

# 사용법

*  타입스크립트에게 리액트 component 설명하는법

1. interface

자바에서도 나오는 interface 개념. 

포인트는 interface라는 것이 object를 설명해준다고 생각하면 된다.

코드를 보면 이해하기가 쉽다.

Circle 이라는 함수가 있고, Circle 의 props에대한 interface를 만든다 했을때, 

그 안에 원하는 property와 type을 적어주면 된다. Circle object를 자세히 설명해주는것이다.

//Circle.tsx
import styled from "styled-components"

interface ContainerProps {
    bgColor:string;
    borderColor?:string;
    text?:string;
}

const Container = styled.div<ContainerProps>`
    width: 200px;
    height: 200px;
    background-color: ${(props) => props.bgColor} ;
    border-radius: 100px;
    border: 1px solid ${(props) => props.borderColor};
`;

interface CircleProps {
    bgColor:string;
    borderColor?: string;
    text?:string;
}

function Circle({bgColor,borderColor,text = "default text"}: ContainerProps){
    return(
        <Container 
        bgColor={bgColor} 
        borderColor={borderColor ?? bgColor}
       >
            {text}
        </Container>
    );
}
export default Circle;


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

const sayHello = (playerObj:PlayerShape) => 
`Hello ${playerObj.name}; you are ${playerObj.age} years old`;

sayHello({name:"minjs",age:14});
sayHello({name: "nico",age:11});
// App.tsx

import styled,{keyframes} from "styled-components";
import Circle from "./Circle";

function App() {
  return (
  <div>
    <Circle borderColor="yellow" bgColor="teal"/>
    <Circle text="I'm here" bgColor="tomato"/>
  </div>
  );
}

export default App;

 

2. optional props

props를 required가 아닌 optional로 주는 방법은 해당 props에 물음표만 붙이면 된다.

그리고 bgColor가 teal인 Circle에만 bordercolor를 주었다. 

interface CircleProps {
    bgColor:string;
    borderColor?: string;
}

 

2-1. js를 이용해서 option 주기

circle props에 text를 추가한다. text="default text"로 그리고 contariner 안에 text를 넣는다.

이번에는 bgcolor가 tomato인 circle에만 text property를 주었다.

그 결과 토마토색 원에만 I'm here이라는 text가 적용되었다.

 

728x90

'Frontend > React' 카테고리의 다른 글

(17) React- React hook form  (0) 2023.01.23
(16) React- Recoil  (0) 2023.01.21
(15) React - styled-components(Themes)  (0) 2023.01.12
(14) React - styled-components(animation / pseudo Selector)  (0) 2023.01.11
(12) React - styled-components / props  (0) 2023.01.11