노마드코더 타입스크립트 강의 정리
하나의 함수가 여러개의 호출 방식(Call Signature)을 가짐
같은 함수 이름이지만 매개변수나 반환 타입이 다를 수 있는 함수를 정의
type FuncSignature = (param: string) => number;
FuncSignature는 매개변수로 String을 받아 number를 반환하는 함수 타입을 정의한 것
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any{
return a+b;
}
console.log(add(10, 20)); //30
console.log(add("Hello,", "Wrold!")); // "Hello, World!"
이렇게 하면 타입스크립트는 함수 호출 시 number / string 중 뭘 전달했는지 체크하고 올바르게 동작하도록 유도
-> 하나의 함수가 여러개의 타입을 처리해야 할 때
type Add = {
(a: number, b: number): number
(a: number, b: string): number
}
const add: Add = (a, b) => {
if(typeof b === "string") return a
return a + b
}
type Config = {
path: string,
state: object
}
type Push = {
(path: string): void
(config: Config): void
}
const push: Push = (config) => {
if(typeof config === "string"){
console.log(config)
}else{
console.log(config.path)
}
}
type Add = {
(a: number, b: number): number
(a: number, b: number, c: number): number,
}
const add: Add = (a, b, c?:number) => {
if(c) return a + b + c
return a + b
}
add(1, 2)
add(1, 2, 3)
function identity<T>(value: T):T {
return value;
}
console.log(identity<number>(10)); //10
console.log(identity<string>("Hello")); // "Hello"
- identity<T> 는 T라는 제네릭 타입을 받아 반환
- 같은 함수를 다양한 타입에서 사용 가능
interface Animal{
makeSound(): void;
}
class Dog implements Animal{
makeSound(){
console.log("멍멍!");
}
}
class Cat implements Animal{
makeSound(){
console.log("야옹~");
}
}
const animals: Animal[] = [new Dog(), new Cat()];
animals.forEach(animal => animal.makeSound());
class Vehicle{
move(){
console.log("이동 수단입니다.");
}
}
class Car extends Vehicle{
move(){
console.log("뛰뛰빵빵");
}
}
class Airplane extends Vehicle{
move(){
console.log("슈우웅");
}
}
const vehicles: Vehicle[] = [new Car(), new Airplane()];
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]): void
}
const superPrint: SuperPrint = (arr) => {
arr.forEach(i => console.log(i));
}
superPrint([1, 2, 3, 4])
superPrint([true, false, true])
superPrint(["a", "b", "c"])
superPrint([1, 2, true, false])
// 알아서 number|boolean으로 처리
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]): TypePlaceholder
}
const superPrint: SuperPrint = (arr) => arr[0]
superPrint([1, 2, 3, 4])
superPrint([true, false, true])
superPrint(["a", "b", "c"])
superPrint([1, 2, true, false, "hello"])
// 출력까지 알아서 처리
type SuperPrint = {
(a: any[]): any
}
const superPrint: SuperPrint = (a) => a[0]
const a = superPrint([1, 2, 3, 4])
const b = superPrint([true, false, true])
const c = superPrint(["a", "b", "c"])
const d = superPrint([1, 2, true, false, "hello"])
d.toUpperCase();
// any를 사용해도 당장은 에러가 발생하지 않지만 출력값에 따라 에러 가능성이 있다.