Enum 과 비슷한 기능을 가진 Literal types ( string 과 number  두가지 타입만 가능)

 object 가 필요한 경우는 interface 이용


// 문자열 literal type
type Job = "police" | "developer" | "teacher";

interface User {
  name: string;
  job: Job;
}

const user: User = {
  name: "Bob",
  job: "teacher", // "police" | "developer" | "teacher" 중에서만 입력 가능
}

interface student {
  name: string;
  grade: 1 | 2 | 3; // literal type 을 이렇게 사용가능
}

 

참고강의 :
https://www.youtube.com/watch?v=QZ8TRIJWCGQ&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=5

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TS] 교차 타입 (Intersection Types)  (0) 2024.03.06
[TS] 유니온 Union Types  (0) 2024.03.06
[TS] 함수 - bind 및 오버로드 이용  (0) 2024.03.06
[TS] 함수  (0) 2024.03.06
[TS] 인터페이스(interface) 사용방법  (0) 2024.03.05

bind 적용 예시

( 참고 : 2024.03.06 - [프로그래밍/JavaScript] - [JS] call, apply, bind )

interface User{
  name: string;
}

const Joey: User = {name: 'Joey'}

function showName(this:User){
  console.log(this.name)
}
const a = showName.bind(Joey);
a() // ' "Joey" 


function showUserInfo(this:User, age: Number, gender : 'm' | 'f'){
  console.log(this.name, age, gender)
}
const b = showUserInfo.bind(Joey);
b(30, 'm') // '"Joey",  30,  "m"

 

 

 

함수의 리턴 값이 매개변수에 따라 다른 경우

interface User{
  name: string;
  age: number;
}

function join(name: string, age: number | string): User | string {
  if (typeof age === "number"){
    return {
      name,
      age
    }
  } else {
    return "나이는 숫자로 입력해주세요."
  }
}

const joey : User = join("Joey", 30); // <- 컴파일 에러 발생
const sam : string = join("sam", "30"); // <- 컴파일 에러 발생

 

해결방법 : 함수 오버로드를 사용

  • 전달받은 매개변수의 개수나 타입에 따라 다른 동작을 하게하는 것을 의미한다.
interface User{
  name: string;
  age: number;
}


function join(name: string, age: number): User; // 함수 오버로드
function join(name: string, age: string): string; // 함수 오버로드
function join(name: string, age: number | string): User | string {
  if (typeof age === "number"){
    return {
      name,
      age
    }
  } else {
    return "나이는 숫자로 입력해주세요."
  }
}

const joey : User = join("Joey", 30);
const sam : string = join("sam", "30");

 

 

참고한 강좌 : https://www.youtube.com/watch?v=prfgfj03_VA&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=4 

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TS] 유니온 Union Types  (0) 2024.03.06
[TS] 리터럴 타입 (Literal Types)  (0) 2024.03.06
[TS] 함수  (0) 2024.03.06
[TS] 인터페이스(interface) 사용방법  (0) 2024.03.05
[TS] 타입스크립트를 사용하는 이유  (0) 2024.03.05

 

call, apply, bind ??

  • call : call 메서드는 모든 함수에서 사용할 수 있으며, this 를 특정값으로 지정할수 있습니다.
    매개변수를 직접받는다.
const joey = {
  name: "Joey"
}

function showName() {
  console.log(this.name);
}

function updateInformation(birthYear, occupation){
  this.birthYear = birthYear;
  this.occupation =occupation;
}

showName.call(joey) // Joey
updateInformation.call(joey, 1987, "developer")
console.log(joey) // {name: "Joey", birthYear: 1987, occupation: "developer"}

 

  • apply : apply 는 함수 매개변수를 배열로 받는 다는 점을 제외하면 call 과 완전히 같은 메서드입니다.
const joey = {
  name: "Joey"
}

function showName() {
  console.log(this.name);
}

function updateInformation(birthYear, occupation){
  this.birthYear = birthYear;
  this.occupation =occupation;
}

showName.apply(joey) // Joey
updateInformation.apply(joey, [1987, "developer"]) // <<< 배열로 변경
console.log(joey) // {name: "Joey", birthYear: 1987, occupation: "developer"}


// 다른예제

const nums = [6,4,10,1]
const minNum = Math.min(...nums); // 1

const minNum2 = Math.min.apply(null, nums); // 1
// = Math.min.apply(null, [6,4,10,1]);

const minNum3 = Math.min.call(null, ...nums); // 1
// = Math.min.apply(null, 6,4,10,1);

 

  • bind : 함수의 this 값을 영구히 바꿀 수 있습니다.
const user = {
  name: "Joey",
  showName : function(){
    console.log(`Hello, ${this.name}`)
  },
}

user.showName(); // "Hello, Joey" 

let fn = user.showName; // fn 에 할당할 때 this 를 잃어버린다.
//fn(); // "Hello, "

fn.call(user);
fn.apply(user);

let bindFn = fn.bind(user);
bindFn()

 

'프로그래밍 > JavaScript' 카테고리의 다른 글

[ JS ] Promise 설명  (0) 2024.05.05
[ JS ] 정렬 sort( )  (0) 2024.04.13
객체(Object), 객체 메소드  (0) 2023.08.03
배열 뒤집기  (0) 2023.07.30
array.reduce()  (0) 2023.07.30

함수 사용 방법

function add(num1: number, num2: number): number{
  return num1 + num2;
}

function addArray(...nums: number[]){
  return nums.reduce((result,num) => result + num, 0);
}

addArray(1,2,3) // 6

// 아무것도 리턴하지 않는 경우는 void
function addVoid(num1: number, num2: number): void{
  console.log(num1 + num2)
}

// ? : 선택 프로퍼티
function hello(name? : string) {
  return `Hello, ${name || "word"}`;
}

const result = hello();
const result2 = hello("Joey");

function helloNameAge(age: number | undefined, name : string) {
  if (age !== undefined){
      return `Hello, ${name}. You are ${age}`;
  }else{
    return `Hello, ${name}`;
  }
}

console.log(helloNameAge(30,'joey'))
console.log(helloNameAge(undefined,'joey'))

 

참고한 강좌 : https://www.youtube.com/watch?v=prfgfj03_VA&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=4 

type Score = 'A' | 'B' | 'C' | 'D' ;

interface User {
  name : string;
  age : number;
  gender? : string;
  readonly birthYear : number;
  [ grade:number ] : Score; 
}

let user: User= {
  name: 'aaa',
  age : 30,
  gender : 'female',
  birthYear : 1990,
  1 : 'A',
  2 : 'C'
};

user.gender = "male"
user.birthYear = 1987; //(error) readonly 여서 변경 불가

 

Interface 로 함수 정의 

interface Add{
  (num1:number, number2:number):number;
}

const add :Add = function(x, y){
  return x + y;
}

add(10, '20') // number가 아니여서 에러
add(10,20) //30

interface IsAudlt {
  (age: number):boolean;
}

const a: IsAudlt = function(x){
  return x > 19 ;
}

a(30) // true​

 

Interface 로 클래스 정의 및 확장

//Implements && extend

interface Car{
  color: string;
  wheels: number;
  start(): void;
}

interface Benz extends Car {
  door : number;
  stop() :void;
}

class Bmw implements Car{
  color;
  wheels = 4;
  constructor(c: string){
    this.color = c;
  }
  start(){
    console.log('go..')
  }
}

const b = new Bmw('blue');
b.start()

const benz :Benz = {
  door: 5,
  stop(){
    console.log('stop...');
  },
  color: 'green',
  wheels: 4,
  start(){
    console.log('go..')
  }
}

 

여러 Interface 로 확장

interface Car{
  color: string;
  wheels: number;
  start(): void;
}
interface Toy{
  name: string;
}

interface ToyCar extends Car, Toy {
  price: number;
}

 

 

참고한 강좌 : https://www.youtube.com/watch?v=prfgfj03_VA&list=PLZKTXPmaJk8KhKQ_BILr1JKCJbR0EGlx0&index=3 

'프로그래밍 > TypeScript' 카테고리의 다른 글

[TS] 유니온 Union Types  (0) 2024.03.06
[TS] 리터럴 타입 (Literal Types)  (0) 2024.03.06
[TS] 함수 - bind 및 오버로드 이용  (0) 2024.03.06
[TS] 함수  (0) 2024.03.06
[TS] 타입스크립트를 사용하는 이유  (0) 2024.03.05

+ Recent posts