본문 바로가기

TIL/기록

[ TIL] 함수에서 타입스크립트 사용하기

 

타입스크립트에서는

파라미터 넘기는 인자부분, 리턴부에서 타입을 지정하는 부분이라고 한다.

 

 

사용하려는 인자 옆에 원하는 타입을 콜론으로 작성해주는 방법이 있다.

function sum(a: number, b: number): number {
	return a + b;
}

 

 

 

type을 object로 넘길 때 ,

object안에 있는 type들을 왼쪽 a, b에서 사용할 수 있게 된다.

그리고 return 부분도 string이 됐으니까 return 할 때 `${ } ` 이렇게  string으로 리턴할 수 있게 해준다. 

function objSum({a, b}: { a: number; b: number }): string{
	return `${a + b}`;
}

 

 

 

 

 

그럼 비동기 함수에서는 어떻게 사용할 수 있을까?

json-server에서 fetch를 통해서 data를 불러오고 그 data를 리턴해주기만하는 아주 간단한 함수다.

async function getPerson() {
	const res = await fetch(`http://localhost:5008/people`);
    if(!res.ok) {
    	throw new Error();
    }
    return res.json();
}

getPerson().then((res) => console.log(res));

 

이렇게하면 콘솔에 찍히는 res에는 아무 타입이나 다 올 수 있다.

 

 

 

type Person = { id: number; age: number; height: number };

async function getPerson():Person[] { // 이렇게만 하면 에러가 뜬다. 왜일까?
	const res = await fetch(`http://localhost:5008/people`);
    if(!res.ok) {
    	throw new Error();
    }
    return res.json();
}

getPerson().then((res) => console.log(res));

 

여기서 getPerson이 반환해주는 것은 Person의 array다.

 

 

근데 getPerson(): Person[] 만 하면 에러가 뜬다. 왜 ?

return type이 async function(비동기함수)인데 Promise가 없어서 에러가 난다.

 

 

 

 

type Person = { id: number; age: number; height: number };

async function getPerson():Promise<Person[]> { // 제네릭으로 바꿔써준다.
	const res = await fetch(`http://localhost:5008/people`);
    if(!res.ok) {
    	throw new Error();
    }
    return res.json();
}

getPerson().then((res) => console.log(res));
// getPerson().then((res) => console.log(res[0].age));

 

이렇게하면 res에도 Person[] 라고 뜬다.

 

 

 

 

 

또 다른 방법으로는

type Person = { id: number; age: number; height: number };

async function getPerson() { 
	const res = await fetch(`http://localhost:5008/people`);
    if(!res.ok) {
    	throw new Error();
    }
    return res.json() as any as Person[];
}

getPerson().then((res) => console.log(res));

 

이렇게 해도 이 getPerson의 type이 return 부에 함수로 자동 추론된다.

이 방법보다는 위의 방법을 추천한다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'TIL > 기록' 카테고리의 다른 글

[TIL] useState에서 typeScript  (0) 2024.03.07
[TIL] generic(제네릭)  (0) 2024.03.06
[TIL] TypeScript 설치  (0) 2024.03.04
[TIL] Mutation  (0) 2024.02.27
[TIL] React Query  (0) 2024.02.24