programing tip

TypeScript에서 '확장'과 '구현'의 차이점은 무엇입니까?

itbloger 2020. 10. 26. 07:44
반응형

TypeScript에서 '확장'과 '구현'의 차이점은 무엇입니까?


남자아이 의 공통점과 차이점 을 알고 싶습니다 .

class Person {
  name: string;
  age: number;
}
class child extends Person {}
class man implements Person {}

짧은 버전

  • extends 방법:

새로운 클래스는 아이입니다 . 상속과 함께 오는 이점을 얻습니다. 모든 속성, 메서드가 부모로 있습니다. 이들 중 일부를 재정의하고 새로 구현할 수 있지만 상위 항목은 이미 포함되어 있습니다.

  • implements 방법:

새로운 클래스 로 취급 할 수 같은 "모양" 하면서, 그 아이가 아닌 . Person부모가 다른 것과 상관없이 필요한 모든 메서드에 전달할 수 있습니다.Person

더 ...

에서 OOP (C #, 자바와 같은 언어) 우리가 사용하는 것

extends상속으로 이익을 얻습니다 ( wiki 참조 ). 작은 인용 :

... 대부분의 클래스 기반 객체 지향 언어에서 상속은 하나의 객체가 부모 객체의 모든 속성과 동작을 획득하는 메커니즘입니다. 상속을 통해 프로그래머는 다음을 수행 할 수 있습니다. 기존 클래스를 기반으로하는 클래스 생성 ...

implements다형성에 더 가깝습니다 ( wiki 참조 ). 작은 인용 :

... 다형성은 서로 다른 유형의 엔티티에 대한 단일 인터페이스를 제공하는 것입니다 ...

그래서 우리는 우리의 class Man.

class Man extends Human ...

그러나 우리가 다른 유형 인 척 할 수 있다고 선언하면- Person:

class Man extends Human 
          implements Person ...

.. Person필요한 곳 어디에서나 사용할 수 있습니다 . 우리는 사람의 사항을 충족해야합니다 "interface" (즉, 모든 공공 물건을 구현) .

implement다른 수업? 정말 멋진 것입니다

Javascript nice face (이점 중 하나) 는 Duck 타이핑 ( wiki 참조 ) 의 내장 지원입니다 . 작은 인용 :

"오리처럼 걷다가 오리처럼 꽥꽥 거리면 오리 일 것입니다."

그래서, 자바 스크립트, 두 개의 서로 다른 개체 경우 ... 하나 유사한 방법있을 것입니다 (예를 render()) 그들은 그것을 기대하고 함수에 전달 될 수있다 :

function(engine){
  engine.render() // any type implementing render() can be passed
}

이를 잃지 않기 위해 Typescript에서 더 많은 유형의 지원을 통해 동일한 작업을 수행 할 수 있습니다. 그리고 그것이

class implements class

의미가있는 역할이 있습니다.

OOP 언어에서 C#... 할 방법이 없습니다 ...

또한 문서는 여기에 도움이됩니다.

클래스를 확장하는 인터페이스

인터페이스 유형이 클래스 유형을 확장하면 해당 구현이 아닌 클래스의 멤버를 상속합니다. 마치 인터페이스가 구현을 제공하지 않고 클래스의 모든 멤버를 선언 한 것과 같습니다. 인터페이스는 기본 클래스의 개인 및 보호 멤버도 상속합니다. 즉, private 또는 protected 멤버로 클래스를 확장하는 인터페이스를 만들 때 해당 인터페이스 유형은 해당 클래스 또는 하위 클래스에 의해서만 구현 될 수 있습니다.

이것은 큰 상속 계층이 있지만 특정 속성을 가진 하위 클래스에서만 코드가 작동하도록 지정하려는 경우에 유용합니다. 하위 클래스는 기본 클래스에서 상속하는 것 외에 관련 될 필요가 없습니다. 예를 들면 :

class Control {
    private state: any;
}

interface SelectableControl extends Control {
    select(): void;
}

class Button extends Control {
    select() { }
}

class TextBox extends Control {
    select() { }
}

class Image extends Control {
}

class Location {
    select() { }
}

그래서

  • extends 의미-부모로부터 모든 것을 얻습니다.
  • implements in this case is almost like implementing an interface. Child object can pretend that it is parent... but it does not get any implementation

In typescript (and some other OO languages) you have classes and interfaces.

An interface has no implementation, it's just a "contract" of what members/method this type has.
For example:

interface Point {
    x: number;
    y: number;
    distance(other: Point): number;
}

Instances who implement this Point interface must have two members of type number: x and y, and one method distance which receives another Point instance and returns a number.
The interface doesn't implement any of those.

Classes are the implementations:

class PointImplementation implements Point {
    public x: number;
    public y: number;

    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    public distance(other: Point): number {
        return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
    }
}

(code in playground)

In your example you treat your Person class once as a class when you extend it and once as an interface when you implement it.
Your code:

class Person {
    name: string;
    age: number;
}
class Child  extends Person {}

class Man implements Person {}

Has a compilation error saying:

Class 'Man' incorrectly implements interface 'Person'.
Property 'name' is missing in type 'Man'.

And that's because interfaces lack implementation.
So if you implement a class then you only take its "contract" without the implementation, so you'll need to do this:

class NoErrorMan implements Person {
    name: string;
    age: number;
}

(code in playground)

Bottom line is that in most cases you want to extend another class and not to implement it.


Great Answer from @nitzan-tomer! Helped me a lot... I extended his demo a bit with:

IPoint interface;
Point implements IPoint;
Point3D extends Point;

And how they behave in functions expecting an IPoint type.

So what I've learned so far and been using as a thumb-rule: if you're using classes and methods expecting generic types, use interfaces as the expected types. And make sure the parent or base-class uses that interface. That way you can use all subclasses in those as far as they implement the interface.

Hier the extended demo


  1. Interface extends interface with shape
  2. Interface extends class with shape
  3. Class implements interface should implements all fields provided by the interface
  4. Class implements class with shape
  5. Class extends class with all fields

extends focus on inherit and implements focus on constraint whether interfaces or classes.

참고URL : https://stackoverflow.com/questions/38834625/whats-the-difference-between-extends-and-implements-in-typescript

반응형