함수를 설명하는 가장 좋은 방법
: 어떤 [타입의] 매게변수를 받고, 어떤 [타입의] 결과값을 반환하는지 이야기
function func(a: number, b: number) { // 자동 추론 -> number
return a + b;
}
// 화살표 함수
const add = (a: number, b: number) => a + b;
// 매게변수
function introduce(name = "나재민", age: number, tall?: number) {
// ? 선택적 매게변수: undefined으로 유니온 타입으로 받음
console.log(`name : ${name}`);
if (typeof tall === "number") {
console.log(`tall : ${tall + 10}`);
}
}
introduce("나재민", 24, 175);
introduce("이제노", 24);
// rest 파라미터 (...rest 가변적길이의 인수를 전달하면 배열로 묶어서 변수에 저장하는 문법)
function getSum(...rest: number[]) {
let sum = 0;
rest.forEach((it) => (sum += it));
return sum;
}
getSum(1, 2, 3); // 6
getSum(1, 2, 3, 4, 5); // 15
** 선택적 매게변수는 필수매게변수 뒤에 와야됨
함수 타입 표현식(Function Type Expression) : 타입별칭을 이용해 함수의 타입을 별도로 정의하는 문법
type Operation = (a: number, b: number) => number;
const add: Operation = (a, b) => a + b;
const sub: Operation = (a, b) => a - b;
const multiply: Operation = (a, b) => a * b;
const divide: Operation = (a, b) => a / b;
const add2: (a: number, b: number) => number = (a, b) => a / b;
호출 시그니처(Call Signature) : 함수타입 표현식과 동일한 기능
type Operation2 = { // 함수도 객체이기 떄문에
(a: number, b: number): number;
name:string; // 프로퍼티 추가 정의 가능
};
const add3: Operation2 = (a, b) => a + b;
const sub3: Operation2 = (a, b) => a - b;
const multiply3: Operation2 = (a, b) => a * b;
const divide3: Operation2 = (a, b) => a / b;
add3(1, 2);
add.name;
함수 타입의 호환성 : 특정 함수 타입을 다른 함수 타입으로 취급해도 괜찮은지 판단
- 반환값이 호환되는가
type A = () => number;
type B = () => 10;
let a: A = () => 10;
let b: B = () => 10;
a = b; // Up Cast
b = a; // ❌ Down Cast
- 매게변수가 호환되는가
1. 매개변수의 갯수가 같을때 : 매개변수를 기준으로 판단할때 Up Cast ❌, Down Cast ⭕️
type Animal = { // 슈퍼타입
name: string;
};
type Dog = { // 서브타입
name: string;
color: string;
};
let animalFunc = (animal: Animal) => {
console.log(animal.name);
};
let dogFunc = (dog: Dog) => {
console.log(dog.name);
console.log(dog.color);
};
animalFunc = dogFunc; // ❌ Up Cast
let testFunc = (animial: Animal) => {
console.log(animial.name);
console.log(animial.color); // ❌ Animal type엔 color 프로퍼티가 없음
};
dogFunc = animalFunc; // ⭕️ Down Cast
let testFunc2 = (dog: Dog) => {
console.log(dog.name);
console.log(dog.color);
};
2. 매개변수의 갯수가 다를때 : 할당하려고 하는 타입의 함수에 매개변수(타입이 같아야 됨)의 갯수가 더 적어야 된다.
// 매개변수의 갯수가 다를 때
type Func1 = (a: number, b: number) => void;
type Func2 = (a: number) => void;
let func1: Func1 = (a, b) => {};
let func2: Func2 = (a) => {};
func1 = func2; // 2개 <- 1개
func2 = func1; // 1개 <- 2개 ❌
함수 오버로딩 : 하나의 함수를 매개변수의 갯수나 타입에 따라 여러가지 버전으로 정의 하는 방법
// 버전들 = 오버로드 시그니처
function func(a: number): void;
function func(a: number, b: number, c: number): void;
// 실제 구현부 = 구현 시그니처
function func(a: number, b?: number, c?: number) {
// 모든 오버로드 시그니처와 호환되어야 함 -> 선택적 매개변수 ? 사용
if (typeof b === "number" && typeof c === "number") {
console.log(a + b + c);
} else {
console.log(a * 20);
}
}
func(); // ❌
func(1); // ⭕️ 버전 1
func(1, 2); // ❌
func(1, 2, 3); // ⭕️ 버전 3
오버로드 시그니처 : 함수를 오버로딩 하기 위해서 각각 매개변수 별로 다른버전을 명시해주기 위해 함수의 구현부 없이 선언식으로만 구성
사용자 정의 타입 가드 : true or false 함수를 이용해 타입가드를 만들도록 도와주는 문법
type Dog = {
name: string;
isBark: boolean;
};
type Cat = {
name: string;
isScratch: boolean;
};
type Animal = Dog | Cat;
// Dog 타입인지 확인하는 타입 가드
function isDog(animal: Animal): animal is Dog {
return (animal as Dog).isBark !== undefined;
}
// Cat 타입인지 확인하는 타입 가드
function isCat(animal: Animal): animal is Cat {
return (animal as Cat).isScratch !== undefined;
}
function warning(animal: Animal) {
if (isDog(animal)) {
console.log(animal.isBark ? "짖습니다" : "안짖습니다");
} else {
console.log(animal.isScratch ? "햘큅니다" : "안햘퀴어요");
}
}
: animal is Dog/Cat 사용해서 isDog/isCat 값이 ture 일때 반환값 타입을 Dog/Cat 타입임을 보장 -> warning 함수에서 타입을 좁힐수 있음
'Front > typescript' 카테고리의 다른 글
클래스 Classes (0) | 2023.08.23 |
---|---|
인터페이스 (0) | 2023.08.23 |
Type 특징 (0) | 2023.08.22 |
type 호환/계층 (0) | 2023.08.22 |
typescript 타입 (0) | 2023.08.21 |