인터페이스는 타입체크를 하기위해, 변수, 함수, 클래스에 사용될수있습니다. ES6에서는 인터페이스를 지원하지 않지만 타입스크립트는 지원합니다. 인터페이스에 선언된 메서드와 프로퍼티의 구현을 강제하여 일관성을 유지합니다.
인터페이스는 타입스크립트의 타입으로 사용할수 있습니다. 인터페이스를 타입으로 선언한 변수는 인터페이스 조건을 만족하여야 합니다.
interface Animal{
skin : string,
animal_type : string,
}
let cat : Animal = { skin: "furry", animal_type : "mammalia"}
인터페이스를 이용하여 함수의 양식도 만들수있다. 함수의 인터페이스에는 피라미터와 리턴 타입을정의 하여야한다.
interface AddFunc{
(num1:number,num2:number):number
}
const addFunc:AddFunc = (num1,num2)=> num1+num2
addFunc(1,2) // expect => 3
클래스 선언문 implements 뒤에 인터페이스를 선언함으로서 다음오는클래스는 인터페이스를 구현하여야한다. 이는 클래스의 일관성을 유지할수있다. 인스터스와 클래스는 프로퍼티와 메소드를 가질수있으나 클래스와는 다르게 인터페이스는 직접 인스턴스를 생성할수는없다.
interface Animal{
skin: string,
animaltype: string,
}
class Cat implements Animal{
constructor(public name : string,
public skin : string,
public animaltype: string){} // interface조건을 최소한 만족해야한다.
}
const banya = new Cat("banya","furry","mammalia") //