1、一个特殊情况
先来观察如下两段代码:
代码段1(正常)
在函数定义时,限制函数返回值为void,那么函数的返回值就必须是空。
function demo():void {
// 返回undefined合法
return undefined
// 以下返回均不合法
return 100
return false
return null
return []
}
demo()
代码段2(特殊)
使用类型声明限制函数返回值为void时,TypeScript并不会严格要求函数返回空。
type LogFunc = () => void
const f1: LogFunc = () => {
return 100; // 允许返回非空值
};
const f2: LogFunc = () => 200; // 允许返回非空值
const f3: LogFunc = function () {
return 300; // 允许返回非空值
};
为什么会这样?
是为了确保如下代码成立,我们知道 Array.prototype.push 的返回值是一个数字,而Array.prototype.forEach方法期望其回调的返回类型是void。
const src = [1, 2, 3];
const dst = [0];
src.forEach((el) => dst.push(el));
官方文档的说明:Assignability of Functions
2、一些相似概念的区别
interface 与 type 的区别
-
相同点:interface和type 都可以用于定义对象结构,在定义对象结构时两者可以互换。
-
不同点:
- interface:更专注于定义对象和类的结构,支持继承、合并。
- type:可以定义类型别名、联合类型、交叉类型,但不支持继承和自动合并。
// 使用 interface 定义 Person 对象
interface PersonInterface {
name: string;
age: number;
speak(): void;
}
// 使用 type 定义 Person 对象
type PersonType = {
name: string;
age: number;
speak(): void;
};
// 使用PersonInterface
/* let person: PersonInterface = {
name:'张三',
age:18,
speak(){
console.log(`我叫:${this.name},年龄:${this.age}`)
}
} */
// 使用PersonType
let person: PersonType = {
name:'张三',
age:18,
speak(){
console.log(`我叫:${this.name},年龄:${this.age}`)
}
}
interface PersonInterface {
name: string // 姓名
age: number // 年龄
}
interface PersonInterface {
speak: () => void
}
interface StudentInterface extends PersonInterface {
grade: string // 年级
}
const student: StudentInterface = {
name: '李四',
age: 18,
grade: '高二',
speak() {
console.log(this.name,this.age,this.grade)
}
}
// 使用 type 定义 Person 类型,并通过交叉类型实现属性的合并
type PersonType = {
name: string; // 姓名
age: number; // 年龄
} & {
speak: () => void;
};
// 使用 type 定义 Student 类型,并通过交叉类型继承 PersonType
type StudentType = PersonType & {
grade: string; // 年级
};
const student: StudentType = {
name: '李四',
age: 18,
grade: '高二',
speak() {
console.log(this.name, this.age, this.grade);
}
};
interface 与 抽象类的区别
-
相同点:都能定义一个类的格式(定义类应遵循的契约)
-
不相同:
- 接口:只能描述结构,不能有任何实现代码,一个类可以实现多个接口。
- 抽象类:既可以包含抽象方法,也可以包含具体方法,一个类只能继承一个抽象类。
// FlyInterface 接口
interface FlyInterface {
fly(): void;
}
// 定义 SwimInterface 接口
interface SwimInterface {
swim(): void;
}
// Duck 类实现了 FlyInterface 和 SwimInterface 两个接口
class Duck implements FlyInterface, SwimInterface {
fly(): void {
console.log('鸭子可以飞');
}
swim(): void {
console.log('鸭子可以游泳');
}
}
// 创建一个 Duck 实例
const duck = new Duck();
duck.fly(); // 输出: 鸭子可以飞
duck.swim(); // 输出: 鸭子可以游泳