TypeScript 공부

hey hey·2022년 3월 5일
0

React 자료

목록 보기
17/18
post-thumbnail

TypeScript

1. TypeScript 란 JavaScript를 기반으로 한 프로그래밍 언어

→ 거의 같지만 다른 단어이다.

2. strongly -typed Language

→ 프로그래밍 언어가 작동하기 전에 type을 확인해준다.

3. 사용법

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

  • : number 로 타입을 지정해 준다.
  • plus(”1”,2) 라고 적으면 오류창이 뜬다.

4. 브라우저는 TS를 못 읽는다 → JS 로 complile 해줘야 한다.

→ 알아서 tsconfig.json 파일을 만들어준다.

시작하기

처음부터 시작하기

$ npx create-react-app my-app --template typescript

$ yarn create react-app my-app --template typescript

기존의 코드에 설정해주기

  1. $ npm install --save typescript @types/node @types/react @types/react-dom @types/jest
  2. 확장명 바꿔주기
  3. 오류창 보면
    • styled-component를 못가져오는 에러가 있는데 마우스를 호버해서 뭔가를 설치한다
    • npm i --save-dev @types/styled-components @types ⇒ type definition : 스타일드 컴포넌트의 소스코드를 보고 Typescript로 보내주고 싶은 내용을 보내준다. → 이 라이브러리가 뭔지 알려주는 역할

인터페이스

= TS에서 prop 을 받아오는 방법

= object 설명해주는 것

App.tsx

  • 내려주는 방법은 똑같다.
<div>
  <Circle bgColor="teal"/>
  <Circle bgColor="tomato"/>
</div>

Circle.tsx

  • 인터페이스로 받아올 값들의 값들의 type을 지정해준다
interface CircleProps {
  bgColor:string;
}
  • 만일 내려줄 때 위의 CircleProps 안의 bgColor 가 없다면?
    • <Circle bgColorX="tomato"/> ⇒ 오류가 표시된다.
const Circle = ({bgColor}:CircleProps)=>{
  return (<Container bgColor ={bgColor}/>)}

const Circle = (props:CircleProps) =>{
	return (<container bgColor ={props.bgColor} />)}

{bgColor}:CircleProps) = bgColor의 타입은 CircleProps의 object이다

  • 하나하나 다 써도 되지만 {bgColor...} 양이 많아지면props:CircleProps 라고 사용하는게 더 편리하다.
  • 다시 내려줄 때는 props에서 받아주면 된다.

→ 컨테이너에서 받아 사용하기

  • 먼저 interface를 만들어주고
interface ContainerProps{
  bgColor:string;
}
  • styled 에서 사용하는 방법은 독특하다.
const Container = styled.div<ContainerProps>`
  width : 200px;
  height : 200px;
  background-color : ${props=>props.bgColor};
  border-radius: 100px ;
`;
  • props사용하는 방법 만 잘 익히면 된다 ${props=>props.bgColor}

Props 안의 값을 필수적이지 않게 하기

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

borderColor? : string ⇒ optional 하게 값을 가진다.

const Circle = (props:CircleProps)=>{
  return (
  <Container bgColor = {props.bgColor} borderColor={props.borderColor??"pink"} />
)}

borderColor={props.borderColor??"pink"}

⇒ 선택적으로 값을 받아오기 때문에 값이 없으면 undefined가 들어오게 된다

결국 값이 없으면 기본값을 만들어 주면 된다.

컨테이너에서 받기

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

borderColor? :string; == borderColor:string | undefined; 이렇게 적어도 무방하다

기본값 저장하기

const Circle = ({bgcolor,borderColor,text="defualt")=>{}

REACT + TypeScript

const [counter,setCounter] = useState(1)

state 값을 하나 만들어 준다 →

초기값이 1이 들어가있으면 counter의 타입은 자동으로 number라고 예측된다.

타입을 예측이 아닌 고정을 하고 싶다면?

useState<number>(0) , useState<string>('1') , useState<number|string>(0)

onChange 함수

const onChange =(event:React.FormEvent<HTMLInputElement>)=>{
  // setValue(e.currentTarget.value)
  const {
    currentTarget:{value}
  } = event
  setValue(value)
}
  • event 에 type 을 설정해준다 . event:React.FormEvent<HTMLInputElement>
  • event.currentTarget.value에 우리의 input 값이 있다.
    • const { cureentTarget :{value}} = event 라고 선언한 뒤
    • value의 값만 빼서 사용도 가능하다.

onSubmit 함수

const onSubmit =(event:React.FormEvent<HTMLFormElement>)=>{
  event.preventDefault();
  console.log("hello",value)
}
  • onChange와 비슷하게 사용 가능하다.
profile
FE - devp

0개의 댓글