인터페이스는 일반적으로 타입 체크를 위해 사용되며 변수, 함수, 클래스에 사용할 수 있다. 인터페이스는 여러가지 타입을 갖는 프로퍼티로 이루어진 새로운 타입을 정의하는 것과 유사하다. 인터페이스에 선언된 프로퍼티 또는 메소드의 구현을 강제하여 일관성을 유지할 수 있도록 하는 것이다.
인터페이스는 프로퍼티와 메소드를 가질 수 있다는 점에서 클래스와 유사하나 직접 인스턴스를 생성할 수 없고 모든 메소드는 추상 메소드이다. 단, 추상 클래스의 추상 메소드와 달리 abstract 키워드를 사용하지 않는다.
interface User { name: string; age: number; greeting(phrase: string): void; } let user1: User; user1 = { name: "Julie", age: 29, greeting(p: string) { console.log(p, `welcome ${this.name}`); //arrow function으로 접근할 경우 this가 window가 되므로 this.name에 접근할 수 없음. }, }; user1.greeting("Test!");
동적 타이핑의 한 종류로, 객체의 변수 및 메소드의 집합이 객체의 타입을 결정하는 것을 말한다. 클래스 상속이나 인터페이스 구현으로 타입을 구분하는 대신, 덕 타이핑은 객체가 어떤 타입에 걸맞은 변수와 메소드를 지니면 객체를 해당 타입에 속하는 것으로 간주한다.
class Duck(){ yell(){ console.log("꽉!") } } class Person(){ yell(){ console.log("사람도 꽉!") } } function everybodyYelling(duck){ duck.yell(); } everybodyYelling(new Duck()); everybodyYelling(new Person())
만약 위 코드에서 Person이나 Duck클래스에 quack메서드가 구현되어 있지 않다면, 런타임 애러를 발생시킬 것이다. 하지만 Typescript
를 사용한다면 덕 타이핑을 할 때 메서드를 검사하지 않고도 런타임 에러를 막을 수 있다. TypeScript의 덕 타이핑은 어떤 객체가 특정 인터페이스에서 명시하는 메소드를 가지고 있다면 해당 객체가 그 인터페이스를 구현한 것으로 보는 것이다.
interface Yellable{ yell(): void } class Duck implements Yellable{ yell(){ console.log("꽥!") } } class Person(){ yell(){ console.log("사람도 꽉!") } } function everybodyYelling(duck){ duck.yell(); } everybodyYelling(new Duck()); everybodyYelling(new Person())
물론 조금 더 strict하게 타이핑을 하고 싶다면 implements 키워드를 사용하여 명시적으로 선언해주는 것도 좋은 방법이다.
readonly
는 읽기전용이다. readonly속성은 TypeScript 의 경우와 같이 표시될 수도 있습니다 . 런타임 시 동작은 변경되지 않고, 표시된 속성은 readonly유형 검사 중에 쓸 수 없다.
interface User { readonly name: string; age: number; greeting(phrase: string): void; } let user1: User; user1 = { name: "Julie", age: 29, greeting(p: string) { console.log(p, `welcome ${this.name}`); //arrow function으로 접근할 경우 this가 window가 되므로 this.name에 접근할 수 없음. }, }; user1.greeting("Test!");
type addFunc= (a:number, b:number) => number; interface addFunc{ (a:number, b:number): number; }