Quiz 1.
아래 코드의 변수 a,b,c,d,e의 타입은 각각 어떻게 추론될까요?
let a = 10;
const b = 20;
const c = [1, 2];
const d = [1, "hello", true];
const e = [1, 2, 3] as const;
Answer
type A = number;
type B = 20;
type C = number[];
type D = (number | string | boolean)[];
type E = [1, 2, 3];
Quiz 2.
다음 요구사항을 만족하는 Animal, DogCat(개냥이) 타입을 완성하세요
- Animal 타입은 Dog 타입일 수도 Cat 타입일 수도 있습니다.
- DogCat 타입은 Dog이자 Cat입니다.
type Dog = {
name: string;
color: string;
};
type Cat = {
name: string;
age: number;
};
Answer
type Animal = Dog | Cat; // Animal 타입은 합집합(유니언) 타입
type DogCat = Dog & Cat; // DogCat 타입은 교집합(인터섹션) 타입
오늘 배운 개념 정리
대수 타입
정의
여러 개의 타입을 합성해서 새롭게 만들어낸 타입으로, 합집합 타입
과 교집합 타입
이 존재한다.
필요성
합집합 타입 (Union Type)
: 여러 타입 중 하나의 타입을 가질 수 있을 때 사용한다. 이를 통해 함수가 다양한 타입의 매개변수를 받을 수 있도록 하거나, 변수가 여러 타입의 값을 가질 수 있도록 할 수 있어, 코드의 유연성을 높여주며, 동일한 로직을 중복 없이 처리할 수 있게 한다.교집합 타입 (Intersection Type)
: 두 개 이상의 타입을 모두 충족하는 새로운 타입을 생성할 때 사용한다. 이를 통해 여러 인터페이스 또는 클래스의 프로퍼티를 모두 가진 객체를 만들 수 있어, 코드의 재사용성을 높이고, 객체지향 프로그래밍의 핵심 원칙인 '상속'을 더욱 효과적으로 구현할 수 있게한다.
=> 코드의 유연성과 재사용성, 안정성을 크게 향상시킬 수 있다.
사용법
// 1. 합집합 - Union Type
let a: string | number;
a = 1;
a = "hello";
//! Type 'boolean' is not assignable to type 'string | number'.
//! a = true;
let a1: string | number | boolean;
a1 = true;
let arr: (number | string | boolean)[] = [1, 2, 3, "hello", true];
type Dog = {
name: string;
color: string;
};
type Person = {
name: string;
language: string;
};
type Union1 = Dog | Person;
let union1: Union1 = {
name: "",
color: "",
};
let union2: Union1 = {
name: "",
language: "",
};
let union3: Union1 = {
name: "",
color: "",
language: "",
};
// Type '{ name: string; }' is not assignable to type 'Union1'.
// 유니언 타입 밖의 경우.
// let union4: Union1 = {
// name: "",
// }
// 2. 교집합 타입 - Intersection Type
let variable: number & string;
type Dog1 = {
name: string;
color: string;
};
type Person1 = {
name: string;
language: string;
};
type Intersection = Dog1 & Person1;
// Type '{ name: string; color: string; }' is not assignable to type 'Intersection'.
// 교집합은 두 타입의 모든 프로퍼티를 포함해야 한다.
// let intersection1: Intersection = {
// name: "",
// color: "",
// };
타입 추론
정의
타입 추론(Type Inference)은 TypeScript 컴파일러가 특정 변수의 타입을 암시적으로 결정하는 과정이다.
즉, 프로그래머가 명시적으로 타입을 지정하지 않아도 TypeScript 컴파일러가 코드를 분석하여 변수의 타입을 자동으로 찾아내는 기능다.
필요성
- 코드의 간결성: 모든 변수에 타입을 명시적으로 지정하지 않아도 되므로 코드가 더 간결해진다. 특히 변수를 초기화하면서 동시에 선언하는 경우에는 대부분의 경우 타입 추론을 통해 타입을 알 수 있다.
- 에러 방지: TypeScript 컴파일러는 타입 추론을 통해 프로그래머의 의도와 다르게 타입이 할당되는 것을 방지한다. 예를 들어, 숫자 타입의 변수에 문자열을 할당하려고 하면 컴파일러가 에러를 발생시켜 이를 방지한다.
- 개발 편의성 증가: 개발 도구의 지원을 받아 코드 작성 시 타입에 따른 자동완성, 문서화, 리팩토링 등의 기능을 이용할 수 있다.
사용법
let a = 10; //% let a: number
let b = "hello"; //% let b: string
let c = {
id: 1,
name: "치현",
profile: {
nickname: "JuniorTunarr",
},
urls: [],
};
//% let c: { id: number; name: string; profile: { nickname: string; }; urls: never[]; }
let { id, name, profile } = c;
let [one, two, three] = [1, "hello", true]; //% let one: number, let two: string, let three: boolean
function func(message: "hello") {
return "hello";
}
let d; // let d: any
d = 10; // d: any => number
d.toFixed();
// Property 'toUpperCase' does not exist on type 'number'.
// d.toUpperCase();
d = "hello"; // d: number => string
d.toUpperCase();
// Property 'toFixed' does not exist on type 'string'.
// d.toFixed();
// const는 타입 추론을 통해 리터럴 타입을 가진다.
const num = 10; // const num: 10. number 리터럴
const str = "hello"; // const str: "hello". string 리터럴
let arr = [1, "string", true]; // let arr: (string | number | boolean)[]
Quiz 1.
아래 코드의 변수 a,b,c,d,e의 타입은 각각 어떻게 추론될까요?
let a = 10;
const b = 20;
const c = [1, 2];
const d = [1, "hello", true];
const e = [1, 2, 3] as const;
Answer
type A = number;
type B = 20;
type C = number[];
type D = (number | string | boolean)[];
type E = [1, 2, 3];
Quiz 2.
다음 요구사항을 만족하는 Animal, DogCat(개냥이) 타입을 완성하세요
- Animal 타입은 Dog 타입일 수도 Cat 타입일 수도 있습니다.
- DogCat 타입은 Dog이자 Cat입니다.
type Dog = {
name: string;
color: string;
};
type Cat = {
name: string;
age: number;
};
Answer
type Animal = Dog | Cat; // Animal 타입은 합집합(유니언) 타입
type DogCat = Dog & Cat; // DogCat 타입은 교집합(인터섹션) 타입
오늘 배운 개념 정리
대수 타입
정의
여러 개의 타입을 합성해서 새롭게 만들어낸 타입으로, 합집합 타입
과 교집합 타입
이 존재한다.
필요성
합집합 타입 (Union Type)
: 여러 타입 중 하나의 타입을 가질 수 있을 때 사용한다. 이를 통해 함수가 다양한 타입의 매개변수를 받을 수 있도록 하거나, 변수가 여러 타입의 값을 가질 수 있도록 할 수 있어, 코드의 유연성을 높여주며, 동일한 로직을 중복 없이 처리할 수 있게 한다.교집합 타입 (Intersection Type)
: 두 개 이상의 타입을 모두 충족하는 새로운 타입을 생성할 때 사용한다. 이를 통해 여러 인터페이스 또는 클래스의 프로퍼티를 모두 가진 객체를 만들 수 있어, 코드의 재사용성을 높이고, 객체지향 프로그래밍의 핵심 원칙인 '상속'을 더욱 효과적으로 구현할 수 있게한다.
=> 코드의 유연성과 재사용성, 안정성을 크게 향상시킬 수 있다.
사용법
// 1. 합집합 - Union Type
let a: string | number;
a = 1;
a = "hello";
//! Type 'boolean' is not assignable to type 'string | number'.
//! a = true;
let a1: string | number | boolean;
a1 = true;
let arr: (number | string | boolean)[] = [1, 2, 3, "hello", true];
type Dog = {
name: string;
color: string;
};
type Person = {
name: string;
language: string;
};
type Union1 = Dog | Person;
let union1: Union1 = {
name: "",
color: "",
};
let union2: Union1 = {
name: "",
language: "",
};
let union3: Union1 = {
name: "",
color: "",
language: "",
};
// Type '{ name: string; }' is not assignable to type 'Union1'.
// 유니언 타입 밖의 경우.
// let union4: Union1 = {
// name: "",
// }
// 2. 교집합 타입 - Intersection Type
let variable: number & string;
type Dog1 = {
name: string;
color: string;
};
type Person1 = {
name: string;
language: string;
};
type Intersection = Dog1 & Person1;
// Type '{ name: string; color: string; }' is not assignable to type 'Intersection'.
// 교집합은 두 타입의 모든 프로퍼티를 포함해야 한다.
// let intersection1: Intersection = {
// name: "",
// color: "",
// };
타입 추론
정의
타입 추론(Type Inference)은 TypeScript 컴파일러가 특정 변수의 타입을 암시적으로 결정하는 과정이다.
즉, 프로그래머가 명시적으로 타입을 지정하지 않아도 TypeScript 컴파일러가 코드를 분석하여 변수의 타입을 자동으로 찾아내는 기능다.
필요성
- 코드의 간결성: 모든 변수에 타입을 명시적으로 지정하지 않아도 되므로 코드가 더 간결해진다. 특히 변수를 초기화하면서 동시에 선언하는 경우에는 대부분의 경우 타입 추론을 통해 타입을 알 수 있다.
- 에러 방지: TypeScript 컴파일러는 타입 추론을 통해 프로그래머의 의도와 다르게 타입이 할당되는 것을 방지한다. 예를 들어, 숫자 타입의 변수에 문자열을 할당하려고 하면 컴파일러가 에러를 발생시켜 이를 방지한다.
- 개발 편의성 증가: 개발 도구의 지원을 받아 코드 작성 시 타입에 따른 자동완성, 문서화, 리팩토링 등의 기능을 이용할 수 있다.
사용법
let a = 10; //% let a: number
let b = "hello"; //% let b: string
let c = {
id: 1,
name: "치현",
profile: {
nickname: "JuniorTunarr",
},
urls: [],
};
//% let c: { id: number; name: string; profile: { nickname: string; }; urls: never[]; }
let { id, name, profile } = c;
let [one, two, three] = [1, "hello", true]; //% let one: number, let two: string, let three: boolean
function func(message: "hello") {
return "hello";
}
let d; // let d: any
d = 10; // d: any => number
d.toFixed();
// Property 'toUpperCase' does not exist on type 'number'.
// d.toUpperCase();
d = "hello"; // d: number => string
d.toUpperCase();
// Property 'toFixed' does not exist on type 'string'.
// d.toFixed();
// const는 타입 추론을 통해 리터럴 타입을 가진다.
const num = 10; // const num: 10. number 리터럴
const str = "hello"; // const str: "hello". string 리터럴
let arr = [1, "string", true]; // let arr: (string | number | boolean)[]