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博客

相关推荐
Jorah20 小时前
1. TypeScript基本语法
javascript·ubuntu·typescript
小白小白从不日白2 天前
TS axios封装
前端·typescript
aimmon2 天前
Superset二次开发之源码DependencyList.tsx 分析
前端·typescript·二次开发·bi·superset
下雪天的夏风3 天前
Vant 按需引入导致 Typescript,eslint 报错问题
前端·typescript·eslint
theMuseCatcher3 天前
Vue3+TypeScript+Vite+Less 开发 H5 项目(amfe-flexible + postcss-pxtorem)
typescript·less·postcss
Qiyandays3 天前
vue + Lodop 制作可视化设计页面 实现打印设计功能(四)
前端·vue.js·typescript
人工智能的苟富贵4 天前
微信小程序中的模块化、组件化开发:完整指南
微信小程序·小程序·typescript
Code blocks6 天前
小试牛刀-区块链Solana多签账户
算法·typescript·区块链·github
shiming88796 天前
Vue 生命周期与 TypeScript:深入理解组件生命周期
前端·vue.js·typescript
Amd7946 天前
Nuxt Kit 的使用指南:从加载到构建
typescript·配置·nuxt·加载·构建·示例·kit