[KDT]FCFE - 6주1일 TypeScript (Interfaces, Classes)

Keunyeong Lee·2021년 12월 27일
0
post-thumbnail

TypeScript

Interfaces

: type을 만들어내는 방식.

function hello1(person:{name: string, age: number}):void {
	console.log(`안녕하세요! ${person.name} 입니다.`);
}

const p1:{name: string, age: number}={
  name: "mark", age: 39,
};
interface Person1 {
  name: string;
  age: number;
}

function hello1(person:Person1):void {
	console.log(`안녕하세요! ${person.name} 입니다.`);
}

const p1:Person1={ name: "mark", age: 39,};

type을 정의하여 사용하기 때문에 코드량이 줄고 중복으로 사용가능하게 한다.

⭐️ js 로 컴파일을 하면

interface 를 통해 type을 정의한 부분은 보이지 않는다.

optional property

?

interface Person2 {
  name: string;
  age?: number;
}

: 없어도 상관없는 프로퍼티 만들기 ( ? )

Indexable type

interface Person3 {
  name: string;
  age?: number;
  [index: string]: any;
}

: 프로퍼티 네임을 넣는 자리의 type을 지정해준다.

const p32 : Person3 = {
  name: "Anna",
  systers: ["sung", "chan"], //[index: string] : any;
};

function in interface

interface Person4 {
  name: string;
  age: number;
  hello(): void;
}

class implements interface

interface IPerson1 {
  name: string
  age?: number;
  hello(): void;
}

class Person Implements Iperson1 {
  name: string;
  age?: number | undefined;
  
  constructor(name: string){
    this.name = name;
  }
  
  function hello(): void {
    console.log(`안녕하세요! ${this.name} 입니다.`)
}

const person: IPerson1 = new Person("Mark");

interface extends interface

iterface IPerson2 {
  name: string;
  age?: number;
}

interface IKorean extends IPerson2 {
  city: string;
}

const k:IKorean = {
  name: "이웅재",
  city: "서울",
}

function interface

Readonly Interface Properties

interface Person8 {
  name: string;
  age?: number;
  readonly gender: string;
}

: 읽기만 하는 프로퍼티 설정.( 타입을 설정하여 의도를 전달 한다.)

type alias vs interface

// type alias
type PersonList = stirng[];

// interface
interface IPersonList {
  [index: number]: string;
}

intersection

interface ErrorHandling {
  seccess: boolean;
  error?: { message: string };
}

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

// type alias
type ArtistsResponseType = ArtistsData & ErrorHandling;

// interface
interface IArtistsResponse extends ArtistsData, ErrorHandling {}

let art: ArtistsResponseType;
let iar: IArtistsResponse;

union types

interface Bird {
  fly(): void;
  layEggs(): void;
}

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

type PetType = Bird | Fish;
  • interface는 어렵다.

Declaration Merging - interface

: 이름을 똑같이 만들면 자동으로 머징 된다.

  • alias 는 안된다. ( 있는데 또 만들었다고 error 표시 )

Classes

  • object를 만드는 blueprint.
  • 클래스 이전에 object를 만드는 기본적인 방법은 function return
  • Javascript 에도 class는 es6 부터 사용가능
  • OOP 를 위한 초석(객체 지향)
  • TypeScript 에서는 클래스도 사용자가 만드는 타입의 하나.
  • class 이름은 대문자로 시작
  • new를 이용하여 class를 통해 object를 만들 수 있다.
  • constructor 를 이용하여 object를 생성하면서 값을 전달할 수 있다.

ts class

  • class 키워드를 이용하여 클래스를 만들 수 있다.
  • JS 로 컴파일되면 es5 의 경우 function으로 변경된다.
profile
🏃🏽 동적인 개발자

0개의 댓글