[TS] TypeScript Interfaces 정리

Toproot·2021년 9월 2일
0

TypeScript

목록 보기
3/5
post-thumbnail

1. What are Interfaces

type의 시작점이므로 매우 중요!🔥

// Person1 인터페이스 생성(타입)
interface Person1 {
    name: string;
    age: number;
}

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

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

hello1(p1);



2. optional property(1)

  • 상황에 따른 옵션
interface Person2 {
    name: string;
    age?: number; // option : ?를 사용해서 선택적 프로퍼티로 설정.
}

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

hello2({name: 'Mark', age: 39});
hello2({name: 'Anna'});



3. optional property(2)

// indexible type
interface Person3 {
    name: string;
    age?: number;
    [index: string] : any; // indexible, perperty 이름을 자유롭게 지정 가능.
}

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

const p31: Person3 = {
    name: 'Mark',
    age: 39,
};

const p32: Person3 = {
    name: "Anna",
    systers: ['Sung', "Chan"],
}

const p33: Person3 = {
    name: 'Bokdaengi',
    // any이기 때문에 객체도 지정 가능.
    father: p31,
    mother: p32,
};

hello3(p33); // p31, p32 다 가능.



4. function in interface

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

const p41: Person4 = {
    name: 'Mark',
    age: 39,
    // 1.
    hello: function(): void{
        console.log(`안녕하세요. ${this.name} 입니다.`);
    },
};
const p42: Person4 = {
    name: 'Mark',
    age: 39,
    // 2.
    hello(this: Person4): void{
        console.log(`안녕하세요. ${this.name} 입니다.`);
    },
};
// const p43: Person4 = {
//     name: 'Mark',
//     age: 39,
//     // 3. arrow 함수 안에서는 this 사용 불가.
//     hello: (this: Person4): void => {
//         console.log(`안녕하세요. ${this.name} 입니다.`);
//     },
// };

p41.hello();
p42.hello();
# node를 사용해서 실행.
node interface4.js

안녕하세요. Mark 입니다.
안녕하세요. Mark 입니다.



5. class implements interface

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

// implements
// interface 내용을 바탕으로 Person 이라는 클래스 생성 가능
class Person implements IPerson1 {
    name: string;
    age?: number | undefined;
    
    // name의 초기값 지정.
    constructor(name: string) {
        this.name = name;
    }

    hello(): void {
        console.log(`안녕하세요! ${this.name} 입니다.`)
    }
}

// class 이름보다는 interface이름을 부르는 것 권장.
const person: IPerson1 = new Person("Mark");
person.hello();



6. interface extends interface

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

// 상속
interface IKorean extends IPerson2 {
    // 속성 추가.
    city: string;
}

// 대규모 프로젝트에서 많이 사용됨.
const k: IKorean = {
    name: "이웅재",
    city: "서울",
};

HTMLDivElement



7. function interface

interface HelloPerson {
    (name: string, age?: number): void;
}

// 함수의 타입체크는 사용하는 const에서만 적용.
// age:number 시 오류 : Type '(name: string, age: number) => void' is not assignable to type 'HelloPerson'.
const helloPerson: HelloPerson = function(name:string) {
    console.log(`안녕하세요! ${name} 입니다.`);
};

// 함수보다는 interface의 프로퍼티 사용.
helloPerson('Mark', 39);



8. Readonly Interface Properties

interface Person8 {
    name: string;
    age?: number;
    // gender 값을 읽기만 하고 변경할 수 없게 하기 위해 유용하게 사용.
    readonly gender: string;
}

const p81: Person8 = {
    name: 'Mark',
    gender: "male",
};

// 수정불가능하기 때문에 오류 발생..
// p81.gender = "female";



9. type alias vs interface

function

// type alias
type EatType = (food: string) => void;

// interface
interface IEat {
	(food: string): void;
}

array

// type alias
type PeronsList = string[];

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

intersection

interface ErrorHandling {
	success: boolean;
	error?: { mesage: string };
}

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

// type alias
type ArtistResponseType = ArtistsData & ErrorHandling;

// interface
interface IArtistResponse extends ArtistsData, ErrorHandling {}

let art: ArtistResponseType;
let iar: IArtistsResponse;

union types

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

type PetType = Bird | Fish;

// PetType은 하나의 interface나 class로 표현하기 어려워 오류 발생

// error TS3312: An interface can only extend an object type or intersection of
// object type with statically known members.
interface IPet extends PetType {}

// error TS2422: A class can only implements an object type or inersection of
// object types with statically known members.
class Pet implements PetType {}

Declaration Merging - interface

interface MergingInterface {
	a: string;
}
interface MergingInterface {
	b: string;
}
// 선언이 하나로 merging 됨.
let mi: MergingInterface;
mi.

Declaration Merging - type alias

type MergingType = {
	a: string;
};
type MergingType = {
	b: string;
};

// 오류 발생 : Duplcate identifier 'MergingType'.
profile
어디로 튈 지 모르는 개발자 로그 🛴

0개의 댓글