[TIL]220502 - typeScript(interface, class)

koseony·2022년 5월 2일

TIL(Today I Learn)

목록 보기
6/19
post-thumbnail

1. interface

interface는 컴파일타임에만 사용된다.

1-1. optional property

  • ?로 설정
    property가 있을수도 있고 없을수도 있는 경우에는 뒤에 ?를 붙인다.

  • 인덱서블 설정

1-2. 인터페이스 안에 function 정의

  • function 키워드로 만들기

  • function 키워드 없이 만들기

1-3. 인터페이스로 클래스 만들기(implements)

1-4. 인터페이스 상속

1-5. 함수를 인터페이스로 만들기

형 맞추기 조심

1-6. Readonly 키워드


읽기전용은 수정할 수 없다.
데이터를 바뀌지 않게 하려면 readonly를 붙여준다.

1-7. type alias VS interface

  • function 표현방식
// type alias
type EatType = (food: string) => void;

// interface
interface IEat {
  (food: string): void;
}
  • array 표현방식
// type alias
type PersonList = string[];

// interface
interface IPersonList{
	[index: number]: string; 
}
  • intersection
interface ErrorHandling{
  success: boolean;
  error: {message: string};
}

interface ArtistsData{
  artists: {name: string}[];
}

// type alias
type ArtistsResponseType = ArtistsData & ErrorHandling;

// interface
interface IArtistsRespone extends ArtistsData, ErrorHandling {}

let art: ArtistsResponseType;
let iar: IArtistsRespone;
  • union types
interface Bird{
  fly(): void;
  layEggs(): void;
}

interface Fish{
  swim(): void;
  layEggs(): void;
}

type PetType = Bird | Fish;

interface Ipet extends PetType {} // error TS2312: An interface can only extend an object type or intersection of types with statically known members

class Pet implememts PetType {} // error TS2422: A class can only implement an object type or intersection of object type with statically known member.
  • interface의 고유한 기능
interface MergingInterface{
  a: string;
}

interface MergingInterface{
  b: string;
}

let mi: MergingInterface;
mi. 
하면 => `a``b`가 나온다.

2. Class

2-1. 클래스 생성

  • object 를 만드는 blueprint(청사진, 설계도)
  • 클래스 이전에 object를 만드는 기본적인 방법은 function
  • JavaScript에도 class는 es6부터 사용 가능
  • OOP를 위한 초석
  • TypeScirpt에서는 클래스도 사용자가 만드는 타입의 하나

constructor를 이용해 테이터를 받는다.

2-2. 클래스 생성자와 초기화

❗age!는 age를 개발자가 나중에 설정해주겠다는 의미이다. 주의!

  • constructor

같은 이름으로 2개를 불러 오려면 age에 ?를 붙인다 대신 age에 undefiend가 올지 number가 올지 모르기때문에 if문을 넣어준다.

❗정리!

2-3. 접근 제어자(Access Modifiers)

2-4. getter, setter

2-5. readonly get


readonly가 붙어있으면 public이든 private이든
초기화되는 영역에서만 값을 세팅할수 있다.

2-6. index signatures in class

동적으로 데이터가 들어갈 때 사용

2-7. static properties & methods

2-8. singletons

클래스로부터 하나의 오브젝트를 생성하는 것

2-9. 상속(inheritance)


2-10. abstract Classes


abstract 클래스는 new를 이용해서 생성할수 없다.

상속을 통해 완성을 해줘야한다.

profile
프론트엔드 개발자

0개의 댓글