TIL 9/23

Rami·2024년 9월 23일

TodayILearn

목록 보기
11/61

크롬앱 2.4

boolean

const amIFat = true;
console.log("amIFat", amIFat);

null

  • 아무 것도 없는 것으로 채워짐. (비어있다기보다 아무것도 없는 상태로 채워진 것)
  • 절대 자연적으로 생기지 않음. 우리가 variable안에 어떤 것이 없다는 것을 확실히 하기 위해 쓰는 것.
const amIPretty = null;  
console.log("amIPretty", amIPretty);

undefined

  • variable은 존재하는데, 정의되지 않은것 (undefined)
  • 컴퓨터 메모리 안에는 존재함(공간있음), but 값이 들어가지 않은 것
let something; 
console.log("something", something);

null 과 undefined 부가설명

1. undefined

  • 정의되지 않은 값을 의미합니다. 즉, 변수는 선언되었지만 값이 할당되지 않은 상태입니다.
  • JavaScript에서 자동으로 할당됩니다. 예를 들어 변수를 선언만 하고 값을 할당하지 않으면, 그 변수는 undefined 값을 가집니다.

예시:

let x;
console.log(x);  // undefined (변수는 선언되었지만, 값이 할당되지 않음)

또한, 함수가 명시적으로 return 값을 주지 않으면 자동으로 undefined를 반환합니다.

function example() {}
console.log(example());  // undefined (return 값이 없음)

2. null

  • 의도적으로 값이 없다는 것을 명시하는 값입니다. 즉, 변수를 명시적으로 비어 있는 상태로 만들 때 사용합니다.
  • 프로그래머가 명시적으로 설정하는 값입니다. null은 값이 없는 것을 나타내지만, 의도적으로 값을 "없음"으로 설정한 경우입니다.

예시:

let y = null;
console.log(y);  // null (값이 없음을 명시적으로 나타냄)

null은 개발자가 명시적으로 값을 '비어있다'고 설정할 때 사용됩니다.

차이점 요약

  1. undefined:

    • 자동으로 할당되는 값.
    • 변수를 선언했지만, 값을 할당하지 않았을 때.
    • 함수가 명시적으로 값을 반환하지 않았을 때.
  2. null:

    • 개발자가 의도적으로 값이 없음을 나타내기 위해 사용.
    • 변수에 아무것도 저장되지 않도록 설정할 때 사용.

예시로 비교:

let a;
let b = null;

console.log(a);  // undefined (변수는 있지만 값이 없음)
console.log(b);  // null (값이 없음을 명시적으로 설정함)

추가적으로 typeof의 차이:

  • typeof undefined"undefined"를 반환합니다.
  • typeof null"object"를 반환합니다. (이건 JavaScript의 설계상 오류지만, 호환성을 위해 계속 유지되고 있습니다.)

예시:

console.log(typeof undefined);  // "undefined"
console.log(typeof null);  // "object" (JavaScript의 초기 설계 오류로 인해)

이 요약을 통해 nullundefined의 차이를 명확히 이해하셨길 바랍니다. undefined자동으로 설정되는 상태이고, null의도적으로 비어있음을 나타내는 상태입니다.



function sayHello(nameOfPerson){
    // console.log("Hello my name is ");
    console.log(nameOfPerson);
}

sayHello("nico");
sayHello("lynn");
sayHello("dal");

function sayHello(nameOfPerson, age){
    console.log("hello my name is " + nameOfPerson + " and i am " + age + "-years old");
}

sayHello("nico", 10);
sayHello("lynn", 20);
sayHello("dal", 30);

기본식

function plus (a,b){
    console.log(a, b);
}

plus(); // undefined undefined

더하기

function plus (a,b){
    console.log(a + b);
}

plus(); // NaN
plus(8, 10); // 18

나누기

function divide(x, y){
    console.log( x / y);
}
divide(30, 10); // 3

object안에 function함수 넣기 1

const player ={
    name : "nico",
    sayHello : function(){
        console.log("hiiiiii");
    }
}

console.log(player.name); // nico
player.sayHello(); // hiiiiii

object안에 function함수 넣기 2

const player ={
    name : "nico",
    sayHello : function(otherPersonName){
        console.log("hiiiiii " + otherPersonName + " nice to meet you");
    }
}

player.sayHello("lynn"); // hiiiiii lynn nice to meet you

타입스크립트 강의

함수오버로딩?

함수 오버로딩하나의 함수 이름여러 개의 서로 다른 매개변수 타입이나 매개변수 개수를 가질 수 있게 하는 기능입니다. 즉, 동일한 함수 이름을 사용하더라도 인수의 타입이나 개수에 따라 다른 방식으로 동작하도록 정의할 수 있는 기능입니다.

함수 오버로딩의 목적

함수 오버로딩을 통해 하나의 함수다양한 상황에서 사용될 수 있습니다. 예를 들어, push라는 함수가 문자열을 받을 때와 객체를 받을 때, 각각 다른 동작을 수행하도록 할 수 있습니다.

함수 오버로딩의 문법

타입스크립트에서 함수 오버로딩은 두 가지 방식으로 정의할 수 있습니다:
1. 시그니처(Signature): 함수가 받을 수 있는 매개변수의 타입을 여러 개 정의합니다.
2. 구현(Implementation): 실제로 구현된 함수입니다. 하나만 존재하며, 시그니처에 맞게 구현합니다.

Push 예시

type Push = {
    (path: string): void;
    (config: { path: string, state: object }): void;
};

Push 타입은 함수 오버로딩을 정의하는 방식으로, 두 가지 시그니처를 가집니다:
1. (path: string): void → 문자열 path만 받는 함수 시그니처
2. (config: { path: string, state: object }): voidConfig 객체를 받는 함수 시그니처

이 두 시그니처는 같은 함수 push에서 처리되지만, 전달되는 매개변수 타입에 따라 다르게 동작합니다.

함수 오버로딩 구조 이해

const push: Push = (config) => {
    if (typeof config === "string") {
        console.log(config); // 문자열 처리
    } else {
        console.log(config.path); // 객체 처리
    }
};

이 함수 push는 두 가지 매개변수 타입을 처리할 수 있습니다:
1. 문자열을 받을 때 → path를 문자열로 사용
2. 객체를 받을 때 → Config 객체에서 path 속성을 사용

함수 오버로딩의 문법적 구조

Push에서 괄호가 두 번 사용되는 형태는 각각 다른 시그니처를 나타냅니다:

type Push = {
    (path: string): void;
    (config: Config): void;
};

여기서 괄호(())는 함수 시그니처를 정의하는 것이며, 첫 번째 괄호는 path: string을 받는 함수의 시그니처, 두 번째 괄호는 Config 객체를 받는 함수의 시그니처입니다.

구현된 함수는 하나지만, 호출되는 방식에 따라 타입스크립트가 이를 다르게 처리할 수 있게 만들어줍니다. 즉, 호출 시 타입스크립트는 전달된 인수가 문자열인지 객체인지에 따라 올바른 시그니처를 선택합니다.

왜 오버로딩을 사용할까?

  • 하나의 함수여러 상황을 처리할 수 있어 코드의 일관성을 유지할 수 있습니다.
  • 타입스크립트는 정적 타입 검사를 수행하므로 컴파일 시점에 타입에 따른 잘못된 호출을 막아줍니다.

예시로 좀 더 명확히

type Config = {
    path: string,
    state: object
}

type Push = {
    (path: string): void;      // 문자열을 받는 함수
    (config: Config): void;    // Config 객체를 받는 함수
}

const push: Push = (input) => {
    if (typeof input === "string") {
        console.log("String Path:", input);
    } else {
        console.log("Config Path:", input.path);
    }
};

// 함수 호출 예시
push("home");                // String Path: home
push({ path: "about", state: {} });  // Config Path: about
  1. push("home")을 호출하면 문자열로 취급하여 첫 번째 시그니처를 따릅니다.
  2. push({ path: "about", state: {} })를 호출하면 객체로 취급하여 두 번째 시그니처를 따릅니다.

결론

  • 함수 오버로딩동일한 함수 이름으로 다양한 인수 타입이나 인수 개수를 처리할 수 있도록 정의하는 방식입니다.
  • Push는 두 가지 호출 형태를 가질 수 있는 함수 오버로딩을 통해 stringConfig 타입을 처리합니다.

오버로딩 강의 예시들

call signature shortcut

type Add = (a: number, b: number) => number

call signature longcut
type Add = {
    (a: number, b: number) : number
}

오버로딩?
: 함수가 서로 다른 여러개의 call signature을 가지고 있을 때 발생.
예시1

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
}

예시2

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); // string인 경우 처리
    } else {
        console.log(config.path); // Config 타입인 경우 처리
    }
};

예시3
: call 파마리터의 개수도 다른 경우

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);
profile
YOLO

0개의 댓글