![](https://s2.loli.net/2022/10/09/31kvp8HRJuoBCfc.jpg)
TypeScript 面试题
面试常见问题
interface 和 type 的区别
1基础数据类型与接口不同,类型别名还可以用于其他类型,如基本类型(原始值)、联合类型、元组
typescript
// primitive
type Name = string;
// union
type PartialPoint = PartialPointX | PartialPointY;
// tuple
type Data = [number, string];
// dom
let div = document.createElement("div");
type B = typeof div;
2.重复定义
接口可以定义多次,会被自动合并为单个接口 。类型别名不可以重复定义
typescript
interface Point {
x: number;
}
interface Point {
y: number;
}
const point: Point = { x: 1, y: 2 };
3.扩展 接口可以扩展类型别名,同理,类型别名页可以扩展接口。但是两者实现扩展的方式不同
接口的扩展时继承,通过 extends 实现。类型别名的扩展是交叉类型,通过 & 来实现
typescript
// 接口扩展接口
interface PointX {
x: number;
}
interface Point extends PointX {
y: number;
}
// ----
// 类型别名扩展类型别名
type PointX = {
x: number;
};
type Point = PointX & {
y: number;
};
// ----
// 接口扩展类型别名
type PointX = {
x: number;
};
interface Point extends PointX {
y: number;
}
// ----
// 类型别名扩展接口
interface PointX {
x: number;
}
type Point = PointX & {
y: number;
};
4.实现 类无法实现定义了联合类型的类型别名
typescript
type PartialPoint = { x: number } | { y: number };
// A class can only implement an object type or
// intersection of object types with statically known members.
class SomePartialPoint implements PartialPoint {
// Error
x = 1;
y = 2;
}
使用 Type 还是 Interface?
有几种常用规则:
在定义公共 API 时(比如编辑一个库)使用 interface,这样可以方便使用者继承接口
在定义组件属性(Props)和状态(State)时,建议使用 type,因为 type的约束性更强
- interface 和 type 在 ts 中是两个不同的概念,但在 React 大部分使用的 case 中,interface 和 type 可以达到相同的功能效果,type 和 interface 最大的区别是:
type 类型不能二次编辑,而 interface 可以随时扩展
- typescript
interface Animal { name: string } // 可以继续在原有属性基础上,添加新属性:color interface Animal { color: string } /********************************/ type Animal = { name: string } // type类型不支持属性扩展 // Error: Duplicate identifier 'Animal' type Animal = { color: string }
不同点:
- type 可用于 string、number、bool、undefined、null,而 interface 只能描述对象(含数组、函数、包装对象、元组)
- 同名 interface 会合并,而同名 type 会报错
- 一个不太重要但是值得说给面试官的区别:type 声明的是类型别名,而 interface 声明的是新类型。
相同点:
- 都能描述对象(含数组、函数、包装对象)
- 都能用于扩展一个类型。type 用交叉类型做到这一点,interface 用 extends 做到这一点。