TypeScript # 2

미숙한 초보 코딩.Js·2019년 9월 15일
1

TypeScript

목록 보기
2/5
post-thumbnail

함수형

function add(x: number, y: number): number {
  // : number은 앞에 값들을 반환한다.
  return x + y;
}

화살표 함수형

const add2 = (a: number, b: number): number => a + b;

함수 오버로딩

JS 에서는 기본적으로 모든 함수가 가변적으로 인자를 받을 수 있다.
함수에 선언한 인자수 만큼 매개변수가 들어와야 한다.

interface Storage {
  a: string;
}

interface ColdStorage {
  b: string;
}

function store(type: "통조림"): Storage;
function store(type: "아이스크림"): ColdStorage;

function store(type: "통조림" | "아이스크림") {
  if (type === "통조림") {
    return { a: "통조림" };
  } else if (type === "아이스크림") {
    return { b: "아이스크림" };
  } else {
    throw new Error("unsupported type");
  }
}

const s = store("통조림");
s.a;

class 형

interface User {
  name: string;
}
interface Product {
  id: string;
  price: number;
}

class Cart {
  user: User;
  private store: object;    // private 은 선언된 class 안에서만 사용할수있다. 그래서 참조 불가
  constructor(user: User) {
    this.user = user;
    this.store = {};
  }
  put(id: string, product: Product) {
    this.store[id] = product;
  }
  get(id: string) {
    return this.store[id];
  }
}

class PromotionCart extends Cart {
	addPromotion();
	this.user << 이 값을 받아올 수 있다.
}

const cartSuyang = new Cart({ name: "suynag" });
const cartJay = new Cart({ name: "jay" });

cartSuynag. 하면 user,get, put 은 참조가 가능하지만 store은 참조 불가

  • 속성
    private => 선언된 class 안에서만 참조가능
    public => default 값 이고 모든 참조 가능
    protected => 선언된 class 안에서만 참조가 가능하지만 private와 다른점은 상속때 값을
    줄 수가 있다. (PromotionCart)
profile
힘들땐 블로그 하나더 적자!!![ Suyang ]

1개의 댓글

comment-user-thumbnail
2019년 9월 18일

const add2 = (a: number, b: number): number => a + b;

화살표 함수 선언할때 재밌는 점은 a+b 를 리턴을 명시하지 않아도 리턴해준다는 거네용

답글 달기