TS — 介面

萬事順意發表於2024-04-18

TS介面通常指的是TypeScript介面,它是TypeScript中用來描述物件的形狀的一種方式。介面可以定義物件的結構,包括屬性、方法和方法的引數型別以及返回值型別。

1.定義介面:

interface Person {
    name: string;
    age: number;
    greet(): void;
}

2.使用介面:

function greetPerson(person: Person) {
    console.log(`Hello, ${person.name}!`);
}

3.可選屬性:

interface Car {
    make: string;
    model: string;
    year?: number; // 可選屬性
}

4.只讀屬性:

interface Point {
    readonly x: number;
    readonly y: number;
}

5.函式型別:

typescript
interface SearchFunc {
    (source: string, subString: string): boolean;
}

6.可索引型別:

interface StringArray {
    [index: number]: string;
}

7.類 型別:

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    setTime(d: Date) {
        this.currentTime = d;
    }
}

8.擴充套件介面:

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

9.混合型別:

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;
}

相關文章