typescript, interface readonly, 확장, interface Function

cptkuk91·2022년 12월 16일
1

TypeScript

목록 보기
10/13
post-thumbnail

interface에서는 public, private 사용할 수 없지만, readonly는 사용할 수 있습니다.

interface Greetable {
	readonly name: string;
    
    greet(phrase: string): void;
}

// 아래 코드 처럼 implements 여러개의 Interface 추가 가능
// class Person implements Greetable, AnotherInterface {}

class Person implements Greetable {
	name: string;
    age = 30;
    
    constructor(n: string){
    	this.name = n;
    }
    
    greet(phrase: string) {
    	console.log(phrase + " " + this.name);
    }
}

let user1: Greetable;

user1 = new Person("max");
// user1.name = "mana"; new Person("max")를 통해 "max"가 설정된 상태라 "mana"를 추가할 수 없습니다.

console.log(user1);
// Person {age: 30, name: "max");

interface 확장

class Person implements를 통해 여러개의 interface를 설정할 수 있지만 비효율적입니다.
이런 경우 Greetable extends Named를 통해 interface를 확장하고 class Person에 implements Greetable만 적어줍니다.

ex) interface 확장 전

interface Named {
	readonly name: string;
}

interface Greetable {
    greet(phrase: string): void;
}

class Person implements Greetable, Named {
	name: string;
    age = 30;
    
    constructor(n: string){
    	this.name = n;
    }
    
    greet(phrase: string) {
    	console.log(phrase + " " + this.name);
    }
}

ex) interface 확장 사용

interface Named {
	readonly name: string;
}

interface Greetable extends Named {
	greet(phrase: string): void;
}

// Greetable에서 interface를 확장했을 때 Greetable에 name이 추가된 상태이기 때문에, class Person 내 name: string설정해야 합니다.
class Person implements Greetable {
	name: string;
    age = 30;
    
    constructor(n: string){
    	this.name = n;
    }
    
    greet(phrase: string) {
    
    }
}

class 상속을 사용하는 경우 하나의 class만 상속할 수 있고, 다수의 class로 부터 상속할 수 없습니다. 하지만 interface는 여러 개 확장할 수 있죠.


함수 type으로서 interface

//type AddFunction = (a: number, b: number) => number;
interface AddFunction {
	(a: number, b: number): number;
}

let add: AddFunction;

// add: AddFunction이기 때문에 아래 n1: number를 string으로 바꿀 경우 작동하지 않는다.
add = (n1: number, n2: number) => {
	return n1 + n2;
};

interface Named {
	readonly name: string;
}

interface Greetable extends Named {
	greet(phrase: string): void;
}

// Greetable에서 interface를 확장했을 때 Greetable에 name이 추가된 상태이기 때문에, class Person 내 name: string설정해야 합니다.
class Person implements Greetable {
	name: string;
    age = 30;
    
    constructor(n: string){
    	this.name = n;
    }
    
    greet(phrase: string) {
    
    }
}
profile
메일은 매일 확인하고 있습니다. 궁금하신 부분이나 틀린 부분에 대한 지적사항이 있으시다면 언제든 편하게 연락 부탁드려요 :)

0개의 댓글