→ 타입들의 이름을 짓는 역할을 하고 코드 안의 계약을 정의, 프로젝트 외부에서 사용하는 코드의 계약을 정의하는 것.
function sayName(obj: { name: string }) {
console.log(obj.name);
}
let persone = { name: "june");
sayName(person};
interface Person {
name: string;
}
function sayName(obj: person) P
console.log(obj.name);
}
let person = {name: "june"};
sayName(person);
인터페이스를 추가하여 함수 매개변수 프로퍼티를 정의할 수 있다.
정의한 프로퍼티 값을 누락하거나 정의하지 않은 값을 인수로 전달 시 컴파일 에러가 발생한다.
→ 인터페이스의 모든 프로퍼티가 필요한건 아니다.
어떤 조건에서만 존재하거나 아예 없을 수도 있다.
?를 붙여서 표시함.interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
→ 객체가 처음 생성될 때만 값 설정이 가능하고, 이후 수정이 불가능함.
프로퍼티 이름 앞에 readonly를 붙여 사용.
interface Point {
readonly x: number
readonly y: number
}
let point: Point = { x: 10, y: 20};
point.x = 5; // Error, readonly를 사용했기 때문에 수정할 수 없어 에러가 발생함.
→ 타입스크립트에서 인터페이스는 함수, 클래스에서 사용할 수 있음.
→ 함수 인자의 타입과 반환 값의 타입을 정의함.
함수의 타입을 정의할때도 사용.
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc; // 함수 타입의 변수 생성
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
} // 같은 타입의 함수 값으로 할당.
→ 클래스가 특정 계약(contract)을 충족하도록 명시적으로 강제한다.
interface Animal {
makeSound(): void
}
class Dog implements Animal {
makeSound(): void {
console.log("멍멍");
}
}
→ 클래스와 마찬가지로 인터페이스도 인터페이스 간의 확장이 가능하다.
interface Animal {
makeSound(): void
}
interface Dog extends Animal {
speed: number
}
class Bulldog implements Dog {
makeSound(): void {
console.log("멍멍");
}
}
extends → 타입의 확장으로 사용된다.
implements →
→ 자바스크립트의 유연하고 동적인 타입 특성에 따라 인터페이스 역시 여러 타입을 조합할 수 있다.
interface Counter {
(start: number): string
interval: number
reset(): void
}
function getCounter(): Counter {
let counter = function (start: number) {} as Counter
counter.interval = 123;
counter.reset = function () {}
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
→ 객체가 할 수 있는 행위들을 전략(strategy)으로 만들어놓고, 동적으로 행위에 수정이 필요할 경우 전략 객체를 새로 생성하여 변경, 주입하여 다른 행위가 가능하도록 하는 디자인 패턴.
class VendingMachine {
pay() {
console.log("cath pay!");
}
}interface PaymentStrategy {
pay(): void
}
class cardPaymentStrategy implements PaymentStrategy {
pay(): void {
console.log("card pay!");
}
}
class cashPaymentStrategy implements PaymentStrategy {
pay(): void {
console.log("cash pay!");
}
}
class VendingMachine {
private paymentStrategy: PaymentStrategy
setPaymentStrategy(paymentStrategy: PaymentStrategy) {
this.paymentStrategy = paymentStrategy
}
pay() {
this.paymentStrategy.pay()
}
}
const vendingMachine = new VendingMachine()
vendingMachine.setPaymentStrategy(new CashPaymentStrategy())
vendingMachine.pay() // cash pay
vendingMachine.setPaymentStrategy(new CardPaymentStrategy())
vendingMachine.pay() // card pay