[TS] 인터페이스

heyhey·2023년 7월 12일
0

TypeScript 🦫

목록 보기
3/5
post-thumbnail

인터페이스는 타입 체크를 위해 사용되며, 변수 함수 클래스에 사용할 수 있다.
인터페이스에 선언된 프로퍼티/메소드의 구현을 강제하여 일관성을 유지하는 것이 목적이다.

  • 모든 메소드는 추상 메소드이다. (but abstract를 작성하지 않는다)

변수와 인터페이스

인터페이스는 변수의 타입으로 사용할 수 있다.
이 인터페이스를 타입으로 선언한 변수는 해당 인터페이스를 준수해야 한다.

interface Person{
  id:number;
  name:string;
  age:number;
}
let person:Person = { 
  id = 4,
  name="ho",
  age:15
}

인터페이스를 사용해 함수 파라미터의 타입을 선언할 수도 있다.

function addPerson(person:Person){
	persons = [...persons,person]
}

함수와 인터페이스

인터페이스는 함수 파라미터 뿐 아니라 함수의 타입으로 사용할 수 있다.
함수의 인터페이스에는 선언된 파라미터 리스트리턴타입을 정의한다.

interface SFunc{
	(someNumber:number):number;
}
const sFunc:SFunc = function(num:number){
  return num * num 
}

클래스와 인터페이스

클래스 선언문에 implements 와 인터페이스를 선언하면, 지정된 인터페이스를 반드시 구현하여야 한다.
클래스의 일관성을 유지할 수 있는 장점을 가질 수 있다.

  • 인터페이스는 프로퍼티와 메소드를 가질 수 있다.
  • 인터페이스는 직접 인스턴스를 생성할 수 없다.
interface ITodo {
  id: number;
  content: string;
  completed: boolean;
  sayHello(): void;
}

// Todo 클래스는 ITodo 인터페이스를 구현하여야 한다.
class Todo implements ITodo {
  constructor (
    public id: number,
    public content: string,
    public completed: boolean
  ) { }
  sayHello(){
    console.log("HELLO")
  }
}

여러 방법들을 합쳐 이런 코드가 생성 가능하다.

interface IPerson {
  name: string;
  sayHello(): void;
}

class Person implements IPerson {
  // 인터페이스에서 정의한 프로퍼티의 구현
  constructor(public name: string) {}

  // 인터페이스에서 정의한 추상 메소드의 구현
  sayHello() {
    console.log(`Hello ${this.name}`);
  }
}
  1. 인터페이스 정의
  2. 클래스 생성(인터페이스 구현)
    • 클래스의 타입은 인터페이스와 동일

function greeter(person: IPerson): void {
  person.sayHello();
}

const me = new Person('Lee');
greeter(me); // Hello Lee
  1. 새로운 함수를 생성하는데, 파라미터로 위의 인터페이스만 가능
    • 이 인터페이스를 구현한 파라미터에서는 인터페이스에 정의된 메소드를 사용 가능

덕 타이핑 (구조적 타이핑)

TS는 해당 인터페이스에서 정의한 프로퍼티나 메소드를 갖고 있다면 그 인터페이스를 구현한 것으로 인정한다.
이걸 덕 타이핑이라고 한다.

interface Person{
  name:number
}
function personCanSayHello(person:Person):void{
  console.log("heelo")
}
const dog = {name:"wal",age:3,animal:"dog"}
personCanSayHello(dog) // heelo

인터페이스를 구현하였다는 것이 타입체크의 유일한 방법은 아니다.
타입체크에서 중요한 것은 값을 실제로 갖고 있는 것이다.

변수 dog는 인터페이스 Person과 일치하지는 않는다.
하지만 name 프로퍼티를 구현했기 때문에 인터페이스에 부합하는 것으로 인정한다.

interface는 개발 단계에서 도움을 주기 위한 것이지, JS의 표준이 아니다.
따라서 js 파일로 트랜스 파일링 하면 인터페이스가 삭제된다.

선택적 프로퍼티

인터페이스의 프로퍼티가 선택적으로 필요할 경우는 선택적 프로퍼티로 뒤에 ?를 붙이며, 생략되어도 에러가 발생하지 않는다.

interface UserInfo {
  username: string;
  password: string;
  age?    : number;
  address?: string;
}

const userInfo: UserInfo = {
  username: 'ungmo2@gmail.com',
  password: '123456'
}

인터페이스 상속

인터페이스는 extends 를 사용해 인터페이스를 상속할 수 있다.

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

interface Student extends Person {
  grade: number;
}

const student: Student =  {
  name: 'Lee',
  age: 20,
  grade: 3
}

복수의 인터페이스도 상속받을 수 있다.

interface Developer {
  skills: string[];
}
interface WebDeveloper extends Person, Developer {}

인터페이스는 클래스도 상속받을 수 있다.

class Person {
  constructor(public name: string, public age: number) {}
}

interface Developer extends Person {
  skills: string[];
}

const developer: Developer =  {
  name: 'Lee',
  age: 20,
  skills: ['HTML', 'CSS', 'JavaScript']
}
profile
주경야독

0개의 댓글