티스토리 뷰

안녕하세요 동기 여러분! 오늘은 유니온 타입의 세 번째 시간으로 타입스크립트가 리턴값을 유니온 타입으로 추론을 한다고 합니다. 그 현장을 함께 보시죠(?)!

 

Inferred Union Return Types

타입스크립트는 유니온 타입으로 리턴되는 값을 추론해서 에러를 띄워주는 아주 무시무시한 녀석입니다.

 

아래의 코드를 봅시다!

type User = {
  id: number,
  username: string
};

function createUser() {
  const randomChance = Math.random() >= 0.5;

  if (randomChance) {
    return { id: 1, username: 'nikko' };
  } else {
    return 'Could not create a user.';
  }
}
  • User라는 타입을 선언하는데 id의 타입은 number로 username의 타입은 string입니다. →타입 에일리어스(Type Aliases)
  • 함수 createUser를 선언하는데 radomChance라는 변수에 'Math.random()는 0.5보다 크거나 같다'를 선언합니다. → 여기서 Math.random() 메서드는 0 이상 1 미만의 부동소수점 난수를 리턴합니다.
  • 만약 randomChance가 0.5보다 크거나 같으면 randomChance는 리턴값이 true가 되므로 { id: 1, username: 'nikko' }를 리턴하고 randomChance가 0.5 미만이면 randomChance는 리턴값이 false가 되므로 'Could not create a user.'를 리턴하게 됩니다. 

 

위의 함수를 이용해 타입스크립트가 리턴하는 값을 진짜 추론하는지 알아봅시다.

const userData: User | string = createUser();
  • createUser();를 userData에 선언하고 타입은 User 타입이나 string으로 오는 유니온 타입을 설정해두었습니다. 컴파일링 해보겠습니다.

에러 없이 넘어갑니다.

 

 

 

const userData: User | number = createUser();
  • 유니온 타입을 User와 number로 설정해두고 컴파일링을 해보겠습니다.

 

타입스크립트는 대단하네요!!!

 


 

오늘의 느낌

예제로 나오는 함수를 만들어 보려다가 실패하고 실패해서 그냥 codecademy의 예제를 그대로 들고 왔다 ㅠ ㅠ

 

함수 코드 출처 codecademy : https://www.codecademy.com/
 

Learn to Code - for Free | Codecademy

Learn the technical skills to get the job you want. Join over 50 million people choosing Codecademy to start a new career (or advance in their current one).

www.codecademy.com

 

'TypeScript' 카테고리의 다른 글

[TypeScript] Common Key Value Pairs  (0) 2022.01.20
[TypeScript] Unions and Arrays  (0) 2022.01.20
[TypeScript] Type Narrowing  (0) 2022.01.19
[TypeScript] Defining Unions  (0) 2022.01.19
[TypeScript] Generic Functions  (0) 2022.01.19
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
28 29 30 31
글 보관함