all is well!!
18.[Ts] Interface 본문
			[Nextjs + Typescript] velog 클론코딩/[ Nextjs + Typescript ] 나를 위한 기록
			
		18.[Ts] Interface
tnqlscho 95 2023. 3. 15. 22:49interface
object의 모양을 알려주고 싶을때 사용한다.
interface는 객체 지향 프로그래밍의 개념이 담겼고 type은 더 유연하다.
type으로 정의할때
type Player = {
    nickname:string,
    healthBar:number
}
interface로 정의할 때
interface Player {
    nickname:string,
    healthBar:number
}
Function makeUser(user: Player) : Player{
   return {
        nickname : ’subin’,
        healthBar : 10
    }
}
interface Hello = string; // interface는 오직 object의 모양만 설정할 수 있기때문에 에러가 난다.
type은 더 유연하기 때문에 다양한 목적으로 사용될 수 있다.
interface처럼 object의 모양을 정할 수 있고 alias도 만들수 있다.
하지만 interface는 오로지 object에만 허용된다.
*abstract class 상속할 때
abstract class User {
    constructor(
        protected firstName:string,
        protected lastName:string,
    ){}
    abstract sayHi(name:stirng):string
    abstract fullName():string
}
class Player extends User{
    fullName(){
        return `${this.firstName} ${lastName}`
    }
    sayHi(name:string){
        return `Hello ${name}. My name is ${fullName}`
    }
}
*abstract class 대신 Interface를 상속할 때
interface User {
    firstName : string,
    lastName : string,
    sayHi(name:stirng) : string
    fullName() : string
}
interface Human {
    health : number
}
// 하나 이상의 interpace를 동시에 상속받을 수 있다.
class Player implements User, Human{ //  abstract class를 상속받을때 쓰는 extends 대신 inplements라는 js가 사용하지 않는 단어를 쓴다.
    constructor(
        public firstName : string, // Interface를 상속할때는 property를 private로는 만들지 못한다.
        public lastName : string,
        public health : number,
    ){}
    fullName(){
        return `${this.firstName} ${lastName}`
    }
    sayHi(name:string){
        return `Hello ${name}. My name is ${fullName}`
    }
}
abstract class는 표준화된 property와 메소드를 갖도록 해주는 설계 도면을 만들기 위해
abstract class를 사용하는데, js에서는 일반적은 class로 바뀐다.
Interface는 컴파일하면 js로 바뀌지않고 사라진다.
그래서 이때 interfacs를 사용한다.
*interpace를 상속하게 만들때 주의해야 할점
1. private, property 사용하지 못한다.
2. abstract class에서는 constructor이 있었지만 interpace를 사용하게 되면 constructor 부분을
상속받는 class에서 일일히 설정해줘야 한다.
*출처 노마드코더 강의
https://nomadcoders.co/typescript-for-beginners/lectures/3681
https://nomadcoders.co/typescript-for-beginners/lectures/3680
'[Nextjs + Typescript] velog 클론코딩 > [ Nextjs + Typescript ] 나를 위한 기록' 카테고리의 다른 글
| [package.json] dependencies / devDependencies 차이 (0) | 2023.03.24 | 
|---|---|
| 17. [Ts] Abstract class (0) | 2023.03.13 | 
| 16. [Ts] Polymorphism / Generic (0) | 2023.03.10 | 
| 15. [Ts] Overloading (0) | 2023.03.08 | 
| 14. [Ts] Call signatures (0) | 2023.03.07 | 
			  Comments