2024.01.30(화)
|
연산자를 사용하여 타입을 여러 개 연결할 수 있음
// 문자열 또는 숫자
function logText(text: string | number) {
// ...
}
&
연산자를 사용하여 여러 타입을 모두 만족하는 하나의 타입을 나타낼 수 있음
interface Person {
name: string;
age: number;
}
interface Developer {
name: string;
skill: number;
}
type Capt = Person & Developer;
/* Capt는 다음과 같이 정의됨
{
name: string;
age: number;
skill: string;
}
*/
타입 별칭은 새로운 타입 값을 하나 생성하는 것이 아니라 정의한 타입에 대해 나중에 쉽게 참고할 수 있게 이름을 부여하는 것
// string 타입을 사용할 때
const name: string = 'capt';
// 타입 별칭을 사용할 때
type MyName = string;
const name: MyName = 'capt';
type CardinalDirection = "North" | "East" | "South" | "West";
let direction: CardinalDirection;
type numOrStr = number | string;
let numStr: numOrStr = 100;
function convertToString(val: numOrStr): string {
return String(val);
}
function convertToNumber(val: numOrStr): number {
return Number(val);
}
➕
interface
vstype alias
🔗
- 이 둘은 매우 비슷함
interface
는 확장이 가능(open)한 반면type alias
은 확장이 불가능(closed)하다는 큰 차이가 있음interface
가 더 나은 error message를 제공하기 때문에type alias
보다는interface
를 사용하는 것이 권장됨😊
typeof
연산자를 이용하여 컴파일러가 타입을 예측할 수 있도록 타입을 좁혀(narrowing)주는 방식
type numOrStr = number | string;
let numStr: numOrStr = 100;
let item: number;
function convertToString(val: numOrStr): string {
item = val; // error TS2322: Type 'numOrStr' is not assignable to type 'number'.
return String(val);
}
typeof
연산자로 타입 검증을 수행한 후 할당하면 에러가 발생하지 않음function convertToString(val: numOrStr): string {
if (typeof val === 'number') {
item = val;
}
return String(val);
}
// Array
let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: string[] = ["apple", "banana", "orange"];
let mixedArray: (number | string)[] = [1, "two", 3, "four"];
let readOnlyArray: ReadonlyArray<number> = [1, 2, 3, 4, 5]; // 읽기 전용 (수정 불가능)
// Tuple: 타입의 순서가 정해져 있음
let greeting: [number, string, boolean] = [1, "hello", true];
// REST 문법이 적용된 매개변수 -> Array로 받음
function sum(a: number, ...nums: number[]): number {
const totalOfNums = 0;
for (let key in nums) {
totalOfNums += nums[key];
}
return a + totalOfNums;
}
class Empolyee {
empName: string;
age: number;
empJob: string;
printEmp = (): void => {
console.log(`${this.empName}의 나이는 ${this.age}이고 직업은 ${this.empJob}입니다.`);ㅁ
}
}
let employee1 = new Empolyee(); // 객체 생성
employee1.empName = "Hwang";
employee1.age = 20;
employee1.empJob = "개발자";
employee1.printEmp(); // Hwang의 나이는 20이고 직업은 개발자입니다.
class Empolyee {
empName: string;
age: number;
empJob: string;
constructor(empName: string, age: number, empJob: string) {
this.empName = empName;
this.age = age;
this.empJob = empJob;
}
printEmp = (): void => {
console.log(`${this.empName}의 나이는 ${this.age}이고 직업은 ${this.empJob}입니다.`);
}
}
let employee1 = new Empolyee("Hwang", 20, "개발자"); // 객체 생성
employee1.printEmp(); // Hwang의 나이는 20이고 직업은 개발자입니다.
constructor()
함수가 자동으로 호출됨class Empolyee {
constructor(
private _empName: string,
private _age: number,
private _empJob: string,
){}
printEmp = (): void => {
console.log(`${this.empName}의 나이는 ${this.age}이고 직업은 ${this.empJob}입니다.`);
}
}
public
으로 지정됨access modifier | 설명 |
---|---|
public | class 내·외부에서 모두 접근 가능 |
private | class 내부에서만 접근 가능 (prefix로 _를 붙이는 naming convention이 있음) |
protected | class나 이 class를 상속받은 class 내부에서만 접근 가능 (외부에서는 private처럼, 자식은 public처럼 사용 가능) |
class Empolyee {
constructor(
private _empName: string,
private _age: number,
private _empJob: string,
){}
printEmp = (): void => {
console.log(`${this._empName}의 나이는 ${this._age}이고 직업은 ${this._empJob}입니다.`);
}
}
let employee1 = new Empolyee("Hwang", 20, "개발자"); // 객체 생성
employee1._empName = "Kim"; // error TS2341: Property '_empName' is private and only accessible within class 'Empolyee'.
employee1.printEmp();
private
으로 정의된 프로퍼티나 메서드를 읽고 쓰기 위한 접근 메서드
get
과 set
키워드를 사용get
만 선언하고 set
을 선언하지 않는 경우에는 자동으로 readonly
로 인식됨instance.getProperty()
, instance.setProperty(value)
와 같이 메소드를 호출하는 방식으로 사용해야 하지만instance.property
, instance.property = value
와 같이 마치 property에 접근하고 값을 할당하는 것처럼 훨씬 간결하고 직관적으로 사용 가능class Empolyee {
constructor(
private _empName: string,
private _age: number,
private _empJob: string,
){}
get empName() {
return this._empName;
}
set empName(value: string) {
this._empName = value;
}
printEmp = (): void => {
console.log(`${this._empName}의 나이는 ${this._age}이고 직업은 ${this._empJob}입니다.`);
}
}
let employee1 = new Empolyee("Hwang", 20, "개발자"); // 객체 생성
employee1.empName = "Kim";
employee1.printEmp(); // Kim의 나이는 20이고 직업은 개발자입니다.