3-ts接口 Interface

定义对象形状可选属性 ?只读属性 readonly函数类型接口接口继承 extends

1、interface

TypeScript 只关心我们传递给 函数参数 的值的_结构_ ------ 它只关心该值是否具有预期的属性。之所以只关注类型的结构和能力,是我们称 TypeScript 为_结构类型_类型系统的原因。

js 复制代码
interface Point {
    x: string,
    y: number,
}

2、接口 interface类型别名 type的区别

类型别名和接口非常类似,大多数情况下你可以自由选择使用哪一个。

几乎所有interface的功能在type中都可以使用。

关键的区别在于 向定义的类型添加属性

类型不能重新打开来添加新属性,而接口则总是可以扩展。

js 复制代码
// interface能够直接使用extends继承其他接口类型的内容
interface Point {
    name: string
}
interface User extends Point {
    age: number
}
function setUser(user: User) {
    user.name; // √
    user.age; // √
}


// type不能使用extends直接继承其他类型的内容,需要使用 &
type Point = {
    name: string
}
type User = Pointer & {
    age: number
}
function setUser(user: User) {
    user.name; // √
    user.age; // √
}
js 复制代码
// interface
inteface Point {
    name: string
}
interface Point {
    age: number
}
function setUser(user:Point) {
    user.name; // √
    user.age; // √
}

// type
type Point {
    name: string
}
type Point {  // Error: Duplicate identifier 'Point'.
    age: number
}
function setUser(user:Point) {
    user.name; // 报错
    user.age; // 报错
}

3、可选属性 ?只读属性 readonly

js 复制代码
interface Point {
    color?: string,
    width?: number,
    readonly height: number,
}

readonly

  1. 在 TypeScript 中,属性也可以被标记为 readonly。虽然这不会改变运行时的任何行为,但在类型检查期间,被标记为 readonly 的属性不能被写入。
  2. 使用 readonly 修饰符并不一定意味着一个值是完全不可变的------换句话说,它的内部内容是可以被改变的。它只是意味着属性本身不能被重新赋值。
  3. 当 TypeScript 检查两个类型是否兼容时,它不会考虑两个类型上的属性是否是 readonly,因此 readonly 属性也可以通过别名进行修改。

可选属性 ?

js 复制代码
interface Point {
    color?: string,
    width?: number,
}
function setPoint(point: Point) {}

// 1. 如果传入得实际参数的属性"小于"定义的属性,则不报错
setPoint({ width: 20; }) // √

// 2. 如果传入得实际参数的属性"大于"定义的属性,则报错(即存在定义的ts不存在的属性)
setPoint({ width: 20, clour: '#fff' }) // 报错,colour不存在定义的类型中

// 解决 【溢出属性】报错问题
// 1. [正统做法] 修改类型声明,从定义类型层面解决问题
// 2. [ 差一点的办法 ] 使用 [ 字符串索引签名 ]
interface Point {
    color?: string,
    width?: number,
    [propName: string]: unknown,
}
// 3. [ 再差一点的办法 ] 使用 [ 类型断言as ]
setPoint({ width: 20, colour: '#fff' } as Point)

4、接口继承 extends, 函数类型接口

js 复制代码
// 接口继承
interface Point {
    name: string
}
interface User {
    age: number
}
interface Finally extends Point, User {
    sex: string
}
js 复制代码
// 函数类型接口
// 在 JavaScript 中,函数除了可以被调用外,还可以拥有属性。然而,函数类型表达式的语法并不允许声明属性。如果我们想描述一个可调用且带有属性的东西,可以在对象类型中写一个 *调用签名*:
interface DescribeFn {
    description: string,
    (someArg: number, arg2: number): bolean
}
function doSomething(fn: DescribeFn) {
    console.log(fn.description + `returned` + fn(6, 2))
}
相关推荐
问心无愧05131 天前
ctf show web入门160 161
前端·笔记
李小白661 天前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
humcomm1 天前
AI编程时代新前端职位
前端·ai编程
好家伙VCC1 天前
Web Components主题热切换方案揭秘
java·前端
甲维斯1 天前
Kimi版超级玛丽效果“惊人”,配额不足5厘米!
前端·人工智能
hboot1 天前
AI工程师第一课 - Python
前端·后端·python
凉菜凉凉1 天前
AI时代,被抛弃的前端
前端·ai
console.log('npc')1 天前
AI前端工程与生成式UI学习路线
前端·人工智能·ui
梦曦i1 天前
uni-router v1.1.1发布:守卫超时保护+路由监听
前端·uni-app
qq_2518364571 天前
基于java Web网络订餐系统设计与实现 源码文档
java·开发语言·前端