
⇒ 하나의 함수를 매개변수의 개수나 타입에 따라 여러가지 버전으로 만드는 문법
하나의 함수 func가 존재
모든 매개변수의 타입은 number
-> Ver1. 매개변수가 1개 => 이 매개변수에 20을 곱한 값 출력
-> Ver2. 매개변수가 3개 => 이 매개변수들을 다 더한 값을 출력
실습
구현부 없이 선언식만 써준다 => 이를 오버로드 시그니쳐라고 부른다.
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);
// func(1, 2);
func(1, 2, 3);
// 1, 3번째 호출에서 오류 발생 -> 오버로드 시그니쳐들 중에 하나의 버전을
// 따라가기 때문이다.
⇒ 함수를 이용해서 입맛대로 타입 가드를 만들 수 있는 방법
type Dog = {
name: string;
isBark: boolean;
};
type Cat = {
name: string;
isScratch: boolean;
};
type Animal = Dog | Cat;
function warning(animal: Animal) {
if ("isBark" in animal) {
// 강아지
} else if ("isScratch" in animal) {
// 고양이
}
}
// 위와 같이 작성하면, 프로퍼티의 이름을 기준으로 타입을 좁히면 직관적으로 좋지않고,
// 프로퍼티 이름이 바뀌게 되면 타입이 제대로 좁히지 않는 경우가 발생한다.
사용법
function isDog(animal: Animal): animal is Dog {
return (animal as Dog).isBark !== undefined;
}
function warning(animal: Animal) {
if (isDog(animal)) {
// 강아지
animal;
} else if ("isScratch" in animal) {
animal;
// 고양이
}
}
⇒ 타입에 이름을 지어주는 또 다른 문법 + 객체의 구조를 정의하는데 특화된 문법(상속, 합침 등의 특수한 기능을 제공함)
type A = {
a: string;
b: number;
};
interface A {
a: string;
b: number;
sayHi: () => void;
}
interface Person {
// readonly도 가능
name: string;
age?: number;
// sayHi: () => void;
// 함수 표현식
sayHi(): void;
sayHi(a: number, b: number): void;
// 호출 시그니쳐
// 메서드
}
const person: Person = {
name: "제노",
age: 27, // 없어도 되는 프로퍼티
sayHi: function () {
console.log("Hi");
},
};
person.sayHi();
person.sayHi(1, 2);
interface Animal {
name: string;
age: number;
}
interface Dog {
name: string;
age: number;
isBark: boolean;
}
interface Cat {
name: string;
age: number;
isScratch: boolean;
}
interface Chicken {
name: string;
age: number;
isFly: boolean;
}
⇒ name, age가 중복된 프로퍼티 정의가 많다.
interface Dog extends Animal {
isBark: boolean;
}
// 확인
const dog: Dog = {
name: "",
color: "",
isBark: true,
};
interface Cat extends Animal {
isScratch: boolean;
}
interface Chicken extends Animal {
isFly: boolean;
}
⇒ interface로 만든 객체 타입이 아닌 type 별칭으로 해도 객체 타입이면 확장 가능하다.
// 다중 확장 가능
// dog와 cat이 가지고 있는 모든 프로퍼티들을 가지고 있는 타입으로도 만들 수 있다.
interface DogCat extends Dog, Cat {}
const dogCat: DogCat = {
name: "",
color: "",
isBark: true,
isScratch: true,
};
type Person = {
name: string;
};
type Person = {
age: number;
};
⇒ type 별칭에서는 동일한 타입을 두번 정의를 하려고 하면 오류가 발생
interface Person {
name: string;
}
interface Person {
age: number;
}
결과
const person: Person = {
name: "",
age: 27,
};
⇒ 각각의 인터페이스들에 정의된 프로퍼티들이 합쳐진 객체 타입으로 정의가 된다.
interface Lib {
a: number;
b: number;
}
const lib: Lib = {
a: 1,
b: 2,
c: "hello", //추가를 해야하는 상황이 있을 때
};
.
.
// 아래와 같이 사용
interface Lib {
c: string;
}
위와 같이 c 프로퍼티를 추가해야 하는 경우에 선언 합침을 통해서 추가할 수 있다.