interface Client {
name : string;
age?: number;
}
const client: Client = {
name: '스폰지밥',
age: 3
}
interface 값이 다른 interface에 중첩이 되는것이 있을때 상속받을수가 있다.
상속받을 것에대해서 extends 를 사용하여서 상속시킬수 있다.
interface Shape {
getArea(): number;
}
// interface를 사용해 Shape 함수의 getArea의 값은 숫자이라고 선언을 먼저해둔다.
class Circle implements Shape {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
// implements 를 이용해서 Shape를 설정값을 사용한다.
getArea() {
return this.radius * this.radius * Math.PI;
}
}
class Rectangle implements Shape {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
const circle = new Circle(5);
const rectangle = new Rectangle(2, 5);
//ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
const shapes: Shape[] = [circle, rectangle];
shapes.forEach(shape => {
console.log("me", shape.getArea());
});
// circle, rectangle은 Shape를 implements 하고 있으니 위처럼 배열안에 넣고 실행시켜도 된다.
위의 예제를 변형 시켜 보겠습니다.
public을 사용하게 되면 좀 더 짧게 사용할 수 있습니다.
class Circle implements Shape {
constructor(public radius: number) {
}
getArea() {
return this.radius * this.radius * Math.PI;
}
}
private을 사용하게 되면 좀 더 짧게 사용할 수 있습니다.
class Rectangle implements Shape {
constructor(private width: number, private height: number) {
}
getArea() {
return this.width * this.height;
}
}
영어의 뜻을 보면 알 수 있겠지만 공용으로 쓸지와 비밀로 쓸지의 차이입니다.
!!! 하지만 tsc 컴파일을 했을대는 차이는 없다. 그냥 ts파일에서만 다를뿐이다.
interface 대신 type 과 = 을 추가합니다.
대부분 type 아니면 interface 중 둘중 하나로 쭉쓰면 됩니다.
type Client = {
name : string;
age? : number;
}
type Menu = Client & {
food : string;
}
// Menu 는 Client 를 상속 받을수가 있다.