function add(a:number, b:number){
return a + b
}
const addd = (aa:number, bb:number) => aa + bb
type Add = (a:number, b:number) => number
const adddd: Add = (a, b) => a + b
Push 타입 예시TypeScript에서 함수 오버로딩을 통해 함수가 여러 가지 입력 형태를 받아 다양한 상황에서 사용할 수 있습니다. 예제로 Push 타입을 정의해 보겠습니다.
Config 타입 정의먼저 Config 타입을 정의합니다. 이 타입은 path와 state라는 두 가지 속성을 가진 객체 형태입니다.
type Config = {
path: string,
state: object
}
Push 타입 정의Push 타입은 함수가 두 가지 형태로 호출될 수 있도록 설정합니다. 이때 호출 시그니처(call signature)를 사용하여 push 함수가 각각 문자열 또는 Config 객체를 인자로 받을 수 있게 합니다.
(path: string): void — string 타입의 path만 받는 형태(config: Config): void — Config 타입의 객체를 받는 형태type Push = {
(path: string): void
(config: Config): void
}
Push 타입 사용 예시Push 타입을 사용하여 push 함수를 정의하고, 두 가지 형태의 인자를 처리할 수 있게 합니다.
const push: Push = (arg: string | Config): void => {
if (typeof arg === "string") {
console.log(`Path로 이동: ${arg}`);
} else {
console.log(`Path: ${arg.path}, 상태:`, arg.state);
}
};
// 사용 예시
push("home"); // Path로 이동: home
push({ path: "home", state: { loggedIn: true } }); // Path: home, 상태: { loggedIn: true }
push("home"): 문자열 형태로 호출하면 path 정보만 가지고 이동합니다.push({ path: "home", state: { loggedIn: true } }): Config 타입의 객체를 넣어 호출하면 path와 함께 추가적인 state 정보를 가지고 동작합니다.이렇게 Push 타입으로 설정된 push 함수는 서로 다른 두 가지 입력 형태를 유연하게 처리할 수 있습니다.
type Player<E> = {
name: string
extraInfo: E
}
const nico : Player<{favFood:string}> = {
name: "nico",
extraInfo: {
favFood: "hamburger"
}
}
type Player<E> = {
name: string
extraInfo: E
}
type NicoExtra = {
favFood: string;
}
type NicoPlayer = Player<NicoExtra>
const nico : NicoPlayer = {
name: "nico",
extraInfo: {
favFood: "hamburger"
}
}
type Words = {
[key:string]:string
}
class Dict {
private words: Words
constructor(){
this.words = {}
}
add(word:Word){
if(this.words[word.term] === undefined){
this.words[word.term] = word.def;
}
}
def(term:string){
return this.words[term]
}
}
class Word {
constructor(
public term : string,
public def: string
){}
}
const kimchi = new Word("kimchi", "한국의 음식");
const dict = new Dict();
dict.add(kimchi);
dict.def("kimchi")