本文系统介绍 TypeScript 中接口(interface)与泛型(generic)的核心用法。涵盖对象类型、索引类型、函数类型及枚举的定义方式,解析接口与 type 关键字的区别、多继承与实现机制。深入讲解泛型函数、接口与类的泛型应用,以及通过继承进行类型约束的方法,帮助开发者掌握类型安全编程的关键技术。
接口
在 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)的类型而不知道具体键值时,都可以进行相应的类型定义。
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 如果重复定义则会报错。

字面量赋值
直接将字面量赋值给变量时,TypeScript 会对字面量进行类型推导,若对象包含多余属性则会报错。

然而,如果是将对象的引用进行赋值,则会执行 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);
如果未显式定义类型,TypeScript 会进行类型推导,结果可能并非预期。例如,字符串字面量可能被推导为具体的字面量类型而非 string 类型。

当存在多个参数时,只需在泛型中定义多个类型参数即可。
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 中并不存在,但在 TypeScript 中都是非常重要的类型注解。
总结
本文到此结束,希望能为您提供帮助,也欢迎您关注本站更多内容!