Typescript 언어의 특징 알아보기

Udemy 강의

Typescript

개념

Typescript = Javascript + A type system 이다.

TS Type System의 특징은 다음과 같다.

  • 개발 중 에러 포착 가능

  • type annotation
  • 개발중에만 active된다

  • 성능 최적화 없음

TS를 작성하지만 실제론 컴파일러에선 JS를 실행하는 것이다!

자세히 말하자면, 사실 JS를 작성하고 Type annotiation 추가하는 것이 TS를 작성하는 것.

이 과정을 풀어서 설명하자면

Typescript code = Javascript with type annotations -> Typescript Compiler -> Plain old Javascript 인 것이다.


json 데이터 받아오기

교육용 Json 사이트 를 접속해서 밑의 resource에 todo를 들어가보자

다양한 데이터들이 나오는데 url에 ‘/1’ 를 추가하면 맨 처음 데이터만 받을 수 있다.

typescript 코드를 작성해서 이 json data를 받아보자.

새로운 디렉토리에

npm install axios

package.json 에 내가 설치한 종속성을 볼 수있다.

index.ts 파일을 만든 후 다음과 같이 입력하자

1
2
3
4
5
6
7
import axios from 'axios';

const url = 'https://jsonplaceholder.typicode.com/todos/1';

axios.get(url).then((response) => {
  console.log(response.data);
});

터미널에 tsc index.ts 를 입력하면

새로운 index.js 파일이 생성된다. 들어가보면 위에서 내가 입력한 코드가 JS로 변환되어있다.

위에서 말했듯 tsc라는 Typescript 컴파일러가 js파일로 변환해준것.

이제 node index.js를 통해 실행하면

{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }

라는 원하는 데이터가 발생함을 알 수 있다.

위 2개를 하나로 통합하려면

ts-node index.ts 를 입력하면 된다. 그럼 똑같이

{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }

가 출력된다.

잘못된 인수 순서

plain 형식을 보다 보기 좋게 만들기 위해 코드를 변경해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import axios from 'axios';

const url = 'https://jsonplaceholder.typicode.com/todos/1';

axios.get(url).then((response) => {
  const todo = response.data;

  const ID = todo.ID;
  const title = todo.Title;
  const finished = todo.finished;

  console.log(`
    The Todo with ID: ${ID}
    Has a title of: ${title}
    Is it finished? ${finished}
  `);
});

실행하면 결과는 다음과 같다.

The Todo with ID: undefined Has a title of: undefined Is it finished? undefined

이유가 뭘까?

위 사이트에서 확인해보면 속성 이름이 ‘id’. ‘title’, ‘completed’ 다. 잘못된 이름을 사용했기 때문에 데이터를 못받았다.

여기서 Typescript는 이 오류를 잡아주지 못했다.

만약 위에 데이터 개체가 ID,Title,finished 라는 속성을 가진다고 각주를 달아놨으면 발생하지 않았을 문제다.

이게 typescript form이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import axios from 'axios';

const url = 'https://jsonplaceholder.typicode.com/todos/1';

// 추가한 코드
interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

axios.get(url).then((response) => {
  const todo = response.data as Todo; // as Todo 추가

  const ID = todo.ID;
  const title = todo.Title;
  const finished = todo.finished;

  console.log(`
    The Todo with ID: ${ID}
    Has a title of: ${title}
    Is it finished? ${finished}
  `);
});

우리가 받을 데이터의 형식을 인터페이스로 지정해준 것. 그리고 as Todo 코드를 통해 지정한 인터페이스 형식으로 받을 것이라고 말해준것이다. 따라서 위와 같이 입력하면 ID, Title, finished에 빨간줄이 생기면서 발생 가능한 오류를 표시해준다.

Property ‘ID’ does not exist on type ‘Todo’. Did you mean ‘id’?ts(2551)

index.ts(6, 5): ‘id’ is declared here.

우리가 받기로한 형식과 받은 것이 다르다는 오류가 뜬다. 오류에 뜬대로 고쳐주고 실행해보자. 변수 이름은 굳이 바꾸지 않아도되지만 보기 편하게 하기 위해 바꾸자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import axios from 'axios';

const url = 'https://jsonplaceholder.typicode.com/todos/1';

interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

axios.get(url).then((response) => {
  const todo = response.data as Todo;

  const id = todo.id;
  const title = todo.title;
  const completed = todo.completed;

  console.log(`
    The Todo with ID: ${id}
    Has a title of: ${title}
    Is it finished? ${completed}
  `);
});

The Todo with ID: 1 Has a title of: delectus aut autem Is it finished? false

데이터를 올바르게 받아서 잘 출력한다!

인수 순서 변경

우리가 작성한 형식대로 출력하는 함수를 만들자. 그 후 호출하는 코드를 작성해본다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import axios from 'axios';

const url = 'https://jsonplaceholder.typicode.com/todos/1';

interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

axios.get(url).then((response) => {
  const todo = response.data as Todo;

  const id = todo.id;
  const title = todo.title;
  const completed = todo.completed;

  logTodo(id, completed, title);
});

const logTodo = (id, title, completed) => {
  console.log(`
    The Todo with ID: ${id}
    Has a title of: ${title}
    Is it finished? ${completed}
  `);
};

ts-node index.ts를 통해 실행해보면 괴상한 오류가 발생한다. 이유는?

함수 정의할때 id,title,completed 순서였지만 호출할때는 id, completed,title 로 순서를 바꿔버렸다. 작성해보면 알겠지만 이 과정에서 빨간줄로 오류 가능성을 표시해주지 않는다.

Typescript를 올바르게 안 쓰거나 일반 JavaScript를 쓰면 코드를 실행하기 전까지 오류를 찾을 수 없다.

함수를 정의할 때 변수의 type을 정의해주었다면, 인수가 잘못 들어왔다는 오류가 발생했을 것이다.

1
2
3
4
5
6
7
const logTodo = (id: number, title: string, completed: boolean) => {
  console.log(`
    The Todo with ID: ${id}
    Has a title of: ${title}
    Is it finished? ${completed}
  `);
};

함수 정의를 이렇게 바꾸면 함수 호출하는 코드에서 completed에 빨간 줄이 생기면서 오류 경고를 한다.

Argument of type ‘boolean’ is not assignable to parameter of type ‘string’.

지정한 형식과 다른 인수가 들어왔다는 오류다.

알맞게 순서를 바꿔주고 실행하면 올바르게 실행된다.