TypeSript2 接口类型interface

接口对象的类型

typescript中,我们定义对象的方式要用关键字interface (接口),我的理解是使用interface来定义一种约束,让数据的结构满足约束的格式。

主要是以下特性

interface接口类型 常用于定义对象 比较两个对象形状是否一致

1.对比形状

//这样写是会报错的 因为我们在person定义了a,b但是对象里面缺少b属性

//使用接口约束的时候不能多一个属性也不能少一个属性

//必须与接口保持一致

interface Person {

b:string,

a:string

}

const person:Person = {

a:"213"

}

2. 重合

interface face1 {

name: string;

}

interface face1 {

age: number;

}

let a1: face1 = {

name: "xx",

age: 20,

}

3. 任意key 索引签名[propName: string]: any; 不确定后端会传是什么类型 最好使用any

interface face1 {

name: string;

propName: string\]: any; } let a5: face1 = { name: "xx", age: 20, c: 123, };

3 ? readeOnly ?是可选的后端可能不传这个值 readeOnly是只读不能改常用于后端的id 及函数

interface face1 {

name: string;

age?: number;

readonly id:number

readonly cb:()=>boolean

}

let a1: face1 = {

id:1,

name: "xx",

cb:()=>{

return false

}

}

a1.cb=()=>{ // 函数被修改了 不期望被修改

return true

}

4 接口继承 extends

interface face1 extends face2 {

name: string;

}

interface face2 {

age: number;

}

let a1: face1 = {

name: "xx",

age: 20,

};

5 接口定义函数类型

interface Person {

b?: string,

readonly a: string,

propName: string\]: any; cb:()=\>void } const person: Person = { a: "213", c: "123", cb:()=\>{ console.log(123) } }

TypeSript3 数组类型-CSDN博客

相关推荐
Data_Adventure4 小时前
Java 与 TypeScript 的“同名方法”之争:重载机制大起底
前端·typescript
夏小花花9 小时前
vue3 ref和reactive的区别和使用场景
前端·javascript·vue.js·typescript
烛阴1 天前
前端必会:如何创建一个可随时取消的定时器
前端·javascript·typescript
日月晨曦1 天前
TypeScript:让JavaScript穿上西装革履
前端·typescript
cvpv1 天前
优雅!太优雅!斯巴拉西!怎么让AI写出最优雅的代码
前端·typescript·trae
江拥羡橙1 天前
【基础-判断】HarmonyOS提供了基础的应用加固安全能力,包括混淆、加密和代码签名能力
安全·华为·typescript·harmonyos
烛阴2 天前
TypeScript 接口入门:定义代码的契约与形态
前端·javascript·typescript
Cheney95012 天前
TypeScript 中,! 是 非空断言操作符
前端·vue.js·typescript
掘金安东尼3 天前
TypeScript条件类型与infer构建类型安全的fetch
前端·javascript·typescript
进阶的小木桩4 天前
Vue 3 + Elementui + TypeScript 实现左侧菜单定位右侧内容
vue.js·elementui·typescript