文章目录
- 1.ts 类型, interface 和 type 区别
- 2.数组有哪些常用的方法?说说他们的用途?
1.ts 类型, interface 和 type 区别
interface 和 type 都能描述类型,但侧重点不一样:
- interface 更适合描述 对象结构、类、可扩展的 API 设计
- type 更灵活,适合 类型别名、联合类型、交叉类型、基础类型、工具化组合
核心区别:
1.interface 支持声明合并,type 不支持
这个是非常经典的区别。
interfaceUser{name:string}interfaceUser{age:number}最终会合并成:
interfaceUser{name:stringage:number}2.interface 用 extends 扩展,type 常用交叉类型 &
interface 扩展
interfaceAnimal{name:string}interfaceDogextendsAnimal{bark:()=>void}type 组合
type Animal={name:string}type Dog=Animal&{bark:()=>void}两者都能实现“组合”,但写法不同,不过要注意一点:type 的 & 是交叉类型,如果两个同名属性冲突,可能会得到很奇怪的结果,甚至变成 never。
面试回答:
interface 和 type 都能描述类型,但 interface 更适合定义对象结构和可扩展的契约,支持声明合并与继承;type 更灵活,除了对象外,还能表示联合类型、交叉类型、元组、基础类型别名等复杂类型。实际开发里,描述对象结构我更常用 interface,做类型组合和联合时更常用 type。
2.数组有哪些常用的方法?说说他们的用途?
数组常用方法我一般按几类来记。
增删类:有 push、pop、shift、unshift,分别用于在数组头尾添加和删除元素;
遍历处理类:有 map、filter、reduce,其中 map 返回映射后的新数组,filter 用于筛选符合条件的元素,reduce 可以把数组累积计算成一个值;
截取类有: slice,用于截取数组的一部分且不改变原数组,splice 则可以在指定位置增删改元素,会修改原数组;
查找类:find、findIndex 用于查找元素,includes 判断数组中是否包含某个值,
其他的,join 可以把数组拼接成字符串,sort 用于排序,fill 用于用固定值填充数组。
拓展了解:
find 是找到第一个满足条件的元素本身,返回的是元素值,不是下标。参数是回调函数
findIndex 找到第一个满足条件的元素下标,返回的是索引。
constarr=[10,20,30]constres=arr.find(item=>item>15)console.log(res)// 20constres=arr.findIndex(item=>item>15)console.log(res)// 1