본문 바로가기

Frontend Study - 2/Typescript

Typescript : 복습정리 - 3 (Rest parameter 타입지정, Generic, 리액트+ 타입스크립트)

 

Rest 파라미터의 타입지정 

 

function test (…x : number[]) {
	console.log(x)
}

test(1,2,3,4)

 

Rest 파라미터를 사용하면 array타입으로 저장이 되기 때문에 array형식으로 타입을 지정해 주어야 한다. 

spread operator와 다르다! spread operator는 배열 혹은 오브젝트 괄호를 벗겨주는 역할을 한다. 

 

 

Destructuring 문법을 사용한 파라미터 작성

const person = { student: true, age: 20 };

const test = ({ student, age } : {student : boolean, age : number} ) => {
  console.log(student, age);
};

test(person); // true 20

 

 

타입 변수도 import, export 할 수 있다. 별도로 관리가 가능한 것. 

 

//a.ts

export type Name = string | boolean;
export type Age = (a :number) => number;
//b.ts

import {Name, Age} from './a'
let 이름 :Name = 'kim';
let 함수 :Age = (a) => { return a + 10 }

 

Generic 함수 만들기. 

타입을 파라미터로 입력하기 

 

예시

function test<MyType>(x : MyType[]) : Mytype {
	return x[0]
}

let a = test<number>([4.2])

let b = test<string>([가, 나])

 

 

Generic 함수 파라미터에 타입지정하기

function test<MyType>(x:MyType) {
	return x - 1   //error!
}

이 경우에는 에러가 난다.

x가 불확실하기 때문이다. 아직 x에 뭘 집어넣을지 모르기 때문. 연산자를 쓸 때는 조심해야겠다. 

 

 

이 때는 extends를 통해 타입파라미터를 제한할수 있다. 타입 파라미터에 타입을 주는 것 .

 

function test<MyType extends number>(x:MyType) { 
	return x - 1 
}

 

여기서 extends는 확장의 개념이 아니라 체크의 개념이다. Mytype이라는 타입에 넣을 수 있는 타입을 number로 제한하는 것. 

정확히는 Mytype의 type이 number와 비슷한 속성을 가지고 있는지 if 문으로 체크하는 문법.

 

interface lengthCheck {
  length : number
}
function 함수<MyType extends lengthCheck>(x: MyType) {
  return x.length
}

let a = 함수<string>('hello')  //가능
let a = 함수<number>(1234) //에러남

이렇게도 쓸 수 있다.

 

 

 

리액트 타입스크립트

 

변수와 함수 만들 때 타입지정을 해주고, 리액트에서 쓰이는 특별한 타입에 대하여 알아야 한다. 

 

컴포넌트와 프롭스의 타입지정.  

 

function App() {
	return (
	<div>
		<Profile name=“철수”></Profile>
	</div>
)}

function Profile(props : {name : string} ) : JSX.Element {
	return ( <div> </div>)
}

 

프롭스의 타입은 오브젝트에 담아야 한다. 

name=“철수” 로 프롭스를 주었을 때 실제로는 { name : “철수” } 이렇게 담겨있기 때문.

그래서 받아올 때 destructuring 문법을 통해 {name} 이렇게 받아올 수 있는 것이다. 

 

프롭스에서 에러가 나는 경우가 많은데, 프롭스 타입지정을 사전에 잘해 두는게 중요하다. 

 

 

state.

state는 타입지정이 자동으로 되기 때문에 신경안써도 된다. 

let [user, setUser] = useState(‘kim’)

이런식으로 지정하면 user의 타입은 자동으로 string으로 지정이 되게 되는 것. 

 

하지만 이 때 user의 타입을 string | number 와 같이 다른 타입도 가능하도록 지정하고 싶다면

let [user, setUser] = useState<number | string>(‘kim’) generic 문법을 통해서 할 수 있다. 

 

 

참고사이트 

코딩애플 타입스크립트 강의 : https://codingapple.com/