原來TypeScript中的介面和泛型這麼好理解
“介面”和“泛型”是 TypeScript 相比於 JavaScript 新增的內容,都用於定義資料型別
前面兩篇文章總結了TypeScript中的 型別註解、函式和類,這一篇一起來看看介面和泛型。
介面
使用 interface 關鍵字來定義資料型別
物件型別
當存在於較長的資料型別約束時,我們可以通過 type 關鍵字 為型別註解起別名,也可以通過介面來定義
type UserType = { name: string; age?: number }; const user: UserType = { name: "kiki", age: 18, }; interface IUserType { name: string; age?: number } const person: IUserType = { name: 'alice', age: 20 }
索引型別
interface 和type定義物件都可以為只知道key的型別,不知道具體 key 值的時候,進行型別的定義
interface ILanguage {
[index: number]: string;
}
const language: ILanguage = {
0: "html",
1: "css",
2: "js",
};
type Score = {
[name: string]: number;
}
const score: Score = {
Chinese: 120,
math: 95,
Englist: 88,
};
函式型別
定義函式時,interface 和 type 的語法稍有不同
interface ISelfType {
(arg: string): string;
}
type LogType = (arg: string) => string;
function print(arg: string, fn: ISelfType, logFn: LogType) {
fn(arg);
logFn(arg);
}
function self(arg: string) {
return arg;
}
console.log(print("hello", self, self));
繼承
介面可以實現多繼承,繼承後的介面具備所有父類的型別註解
interface ISwim { swimming: () => void; } interface IEat { eating: () => void; } interface IBird extends ISwim, IEat {} const bird: IBird = { swimming() {}, eating() {}, };
交叉型別
交叉型別其實是與的操作,用 & 符號,將介面進行與操作後,實質上需要滿足所有與操作介面的型別註解
interface ISwim {
swimming: () => void;
}
interface IEat {
eating: () => void;
}
type Fish = ISwim | IEat;
type Bird = ISwim & IEat;
const fish: Fish = {
swimming() {},
};
const bird: Bird = {
swimming() {},
eating() {},
};
export {}
介面實現
介面可以通過類使用 implements 關鍵字來實現,類只能繼承一個父類,但是可以實現多個介面
interface ISwim {
swimming: () => void
}
interface IEat {
eating: () => void
}
class Animal {}
class Fish extends Animal implements ISwim, IEat {
swimming(){}
eating(){}
}
class Person implements ISwim {
swimming(){}
}
function swimAction(iswim: ISwim){
iswim.swimming()
}
swimAction(new Fish())
swimAction(new Person())
沒有實現介面的類,自然是沒有該介面中的方法
interface 和 type 的區別
很多時候 interface 和 type 是相同的,但有一個明顯區別在於 interface 可以重複定義,型別註解會累加,而 type 重複定義會報錯
字面量賦值
直接把字面量賦值型別給變數時,會對字面量進行型別推導,多出的屬性會報錯
但是將物件的引用賦值的話,會進行 freshness 擦除操作,型別檢測時將多餘的屬性擦除,如果依然滿足型別就可以賦值
列舉型別
列舉型別通過 enum 關鍵字來定義,它和聯合型別實現的功能類似,但是列舉型別的程式碼閱讀性會更強一些
enum Direction {
LEFT,
RIGHT,
TOP,
BOTTOM,
}
function turnDirection(direction: Direction) {
switch (direction) {
case Direction.LEFT:
break;
case Direction.RIGHT:
break;
case Direction.TOP:
break;
case Direction.BOTTOM:
break;
default:
const foo: never = direction;
break;
}
}
turnDirection(Direction.LEFT);
泛型
泛型函式
當不確定入參的型別時,可以定義型別註解為泛型,使用的時候再指定具體型別,使用 <> 來進行泛型的定義。
function self<T>(element: T) {
return element;
}
self<string>("alice");
self<number>(2);
self<null>(null);
如果沒有定義型別,ts會進行型別推導,有可能並不是我們希望的型別,如以下字串推匯出來不是”string“字串型別,而是“hello”字面量型別。
當存在多個引數時,在泛型中定義多個即可
function foo<T, E, O>(a: T, b: E, c: O){}
foo(1, 'alice', false)
foo(['alice'], undefined, null)
泛型介面
在介面中使用泛型,將型別註解寫在介面名後
interface Person<T, E> {
name: T;
age: E;
}
const person: Person<string, number> = {
name: "alice",
age: 20,
};
在介面中使用泛型是無法進行型別推導的,使用的時候必須指定具體的型別
除非在介面定義的時候給泛型設定了預設值
interface Book<T = string, E = number> {
category: T;
price: E;
}
const book: Book = {
category: "nature",
price: 88.6,
};
const dictionary: Book<number, string> = {
category: 1,
price: '88'
}
泛型類
類中定義的方式,只是將具體的資料型別替換成了泛型,在類中是可以進行型別推導的
class Point<T> {
x: T;
y: T;
z: T;
constructor(x: T, y: T, z: T) {
this.x = x;
this.y = y;
this.z = z;
}
}
new Point("1.55", "2.34", "3.67");
new Point(1.55, 2.34, 3.67);
型別約束
泛型可以通過繼承來進行型別約束
只需要傳入的引數滿足泛型的條件,即有 length 屬性
interface ILength {
length: number;
}
function getLength<T extends ILength>(element: T) {
return element.length;
}
getLength("alice");
getLength(["alice", "kiki", "lucy"]);
getLength({ length: 5 });
介面、列舉、泛型 這些型別在JavaScript都是沒有的,但在TypeScirpt中都是非常重要的型別註解。
以上就是關於TypeScript介面和泛型的內容,關於js和ts,還有很多需要開發者掌握的地方,可以看看我寫的其他博文,持續更新中~