타이프 라이터 정말 향기 시리즈 - 인터페이스

머리말

내용 타이프 라이터 정말 향기 참조 일련의 중국어 문서 일부 지역은 심도있는 연구가 될 것이기 때문하지만, 문서의 기본 텍스트의 예는, 예를 반복하지 않을 것이다. 또한, 본 논문의 결과는 자바 스크립트 GET로 컴파일되지 않은 코드에서 오류의 몇 가지 예입니다. 실제로 자바 스크립트 코드로 컴파일 타이프 라이터를보고 싶은 경우에, 당신은의 타이프 라이터를 액세스 할 수있는 온라인 컴파일 주소 실습, 더 인상적.

개념

핵심 원리 타이프 값 중 하나 구조체 타입 검사를 갖는다. 그것은 때로는 "오리 형 확인 방법"또는라고 "구조 하위 유형." 타이프에서, 인터페이스의 역할의 이름은 당신의 코드 나 타사 코드는 계약 이러한 유형의 정의된다. 출현 인터페이스는, 우리가 감지하고 많은 문제를 방지하고 개발에 우리의 개발 효율을 향상시킬 수 있다고 할 수있다.

인터페이스 기본

객체 지향 프로그래밍에서, 동작과 동작 사양을 정의하는 인터페이스 사양의 정의. 다음 예제와 같이 :

interface IDo {
    work:string;
    time:number;
}
interface IMan {
    age:number;
    name:string;
    do:Do;
}

let james: IMan = {
    name: 'james',
    age: 35,
    do: {
        work: 'player',
        time: 2020
    }
}
james.name; //"james"
james.do.work; //"player"

우리가 제임스 번호 (12)에 기록 된 이름을 입력하면 그 숫자 형, 또는 쓰기 나이하지 않았다. 그런 다음 오류 메시지가 나타납니다.

옵션 속성

우리의 개발에서, 인터페이스는 특정 조건 하에서, 어떤 조건의 존재, 때로는 모든 필요하지 속성과 존재하지 않습니다.

interface IMan {
    age?:number;
    name:string;
}
let james: IMan = {
    name:"james"
}

읽기 전용 속성

객체가 방금 만든 때 값이 일부 개체 속성은 수정 될 수 있습니다.

interface IMan {
    age:number;
    readonly name:string;
}
let james: IMan = {
    name:"james",
    age:35
}
james.name = "mike"; // error: Cannot assign to 'name' because it is a read-only property.

추가로 관리자

우리가 특별한 목적의 사용과 같은 몇 가지 추가 속성을 가질 수있는 개체를 확인할 수 있습니다 때, 가장 좋은 방법은 문자열 인덱스 서명을 추가하는 것입니다.

interface IMan {
    age:number;
    readonly name:string;
    [propName: string]: any;
}
let james: IMan = {
    name:"james",
    age: 35,
    work:"player"
}

기능 유형

우리는 인터페이스와 기능의 유형을 표시 할 수 있습니다와 같은 기능, 개체입니다.

interface IFunc {
    (x: string, y: string): string;
}
let func: IFunc = function(x: string, y: string){
    return x + y;
}
func("1", "!"); // "1!"

유형 검사의 기능 유형의 경우, 함수의 매개 변수 이름에 정의 된 인터페이스의 이름과 일치 할 필요는 없습니다.

interface IFunc {
    (x: string, y: string): string;
}
let func: IFunc = function(a: string, b: string){
    return a + b;
}
func("1", "!"); // "1!"

색인 유형

배열과 객체를 제한하는 데 사용할 수 있습니다.

interface IMan {
    [index:number]:string
}
//数组
let man1: IMan;
man1 = ["james", "wade", "bosh"];
//对象
let man2: Man;
man2 = {1:"haha", 2:"666"};
console.log(man1); //["james", "wade", "bosh"]
console.log(man2); //{1: "haha", 2: "666"}

클래스 유형

타이프 라이터 인터페이스가 명시 적으로 특정 요구 사항을 충족하기 위해 클래스를 강제로 사용할 수 있습니다, 당신은 달성하기 위해 구현을 사용할 수 있습니다.

interface IMan {
    name:string;
    play(val:string):void;
}

class IFootballer implements IMan {
    name:string
    constructor(name:string){
        this.name = name
    }
    play(val:string){
        console.log(this.name + '踢'+ val)
    }
}

class IBasketballer implements IMan {
    name: string
    constructor(name:string){
        this.name = name
    }
    play(val:string){
        console.log(this.name + '打'+ val)
    }
}
var a = new Footballer('武磊')
a.play("足球") //武磊踢足球

var b = new Basketballer ('姚明')
b.play("篮球") //姚明打篮球

인터페이스 상속

그리고 인터페이스 사이에 우리의 클래스는 서로 상속 할 수 있습니다.
나는

nterface IMan {
    name: string;
}
interface IPlayer extends IMan {
    types:string
}

class IFootballer implements IPlayer {
    name: string;
    types: string;
    constructor(name:string, types:string){
        this.name = name;
        this.types = types
    }
    play(){
        console.log(this.name+ "是" + this.types)
    }
}

let a = new Footballer("c罗", "足球运动员");
a.play(); //c罗是足球运动员

인터페이스는 콤마로 분리 된 복수의 인터페이스를 상속받을 수있다.

interface IMan {
    name: string;
}
interface ICity {
    city:string;
}
interface IPlayer extends IMan,ICity {
    types:string
}

혼합 유형
우리는 종류의 다양한 동시에 객체를 만들 수 있습니다.

interface ICounter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): ICounter {
    let counter = <ICounter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

인터페이스 상속 클래스

클래스가 인터페이스 유형을 상속 할 때, 클래스의 멤버를 상속하지만 그 구현에 포함되지 않습니다. 인터페이스와 마찬가지로 모든 클래스의 멤버가 존재 선언하지만 같은 구현을 제공하지 않습니다. 인터페이스는 클래스의 개인 보호 회원을 상속합니다. 당신은 클래스가이 인터페이스의 개인 또는 보호 된 멤버가이 클래스 또는 하위 클래스에 의해 구현 될 수있는 경우에 상속 된 인터페이스를 만들 때 (실행)하는 것이이 의미합니다.
우리는 거대한 상속 구조를 가질 때 유용하지만, 특정 하위 클래스 속성이있을 때 우리의 코드에만 작동 지적 할 때. 다음 클래스에 열리는 서브 클래스에 추가하여 기본 클래스와는 아무 상관이있다.

class Control {
    private state: any;
}

interface ISelectableControl extends IControl {
    select(): void;
}

class Button extends Control implements ISelectableControl {
    select() { }
}

class TextBox extends Control {
    select() { }
}

// 错误:“Image”类型缺少“state”属性。
class Image implements ISelectableControl {
    select() { }
}
//error
class Location {

}

참고

https://github.com/zhongsp/TypeScript

최종적으로

- 일부 지역에서 텍스트가없는 부정확하거나 잘못된 장소 경우, 것을 환영합니다, 자신의 이해의 일부를 추가 할 수 있습니다
내가 당신에게 모두 새해 복 많이 받으세요, 가족 Fu-을 기원합니다!
일선 의료 종사자가 바이러스를 물리 치기 위해 가능한 한 빨리, 건강을 유지하고 싶다!
난 당신이 완벽하게 건강 희망!

출시 사 원저 · 원 찬양 4 · 전망 (92)

추천

출처blog.csdn.net/qq_42002487/article/details/104079434