typeScript学习-TS类型-接口
typeScript学习
接口:
定义:另一种定义对象类型的类型
接口应用场景:
1、一些第三方包或者框架底层源码中有大量的接口类型
2、提供方法的对象类型的参数时使用
3、为多个同类别的类提供统一的方法和属性声明
如何定义接口:
继承接口:
新的接口只是在原来接口集成之上增加了一些属性或方法,这是就用接口继承
// 继承 // 宠物 interface Pet { name: string, love: number, health: number, toHeallth(): void, } // 狗 interface Dog extends Pet { strain: string, // 品种 guradHome(): void, }
可索引签名:
// 可索引签名 interface Product { name: string, price: number, account: number, [x: string]: any } let p: Product = { name: 'zhangsan', price: 100, account: 10, descri1: "ok", stockno: 1000, [Symbol('stockno1')]: 1000, 100: 'abc', true: 1 } interface Product2 { name: string, price: number, account: number, [x: number]: any } let p2: Product2 = { name: 'zhangsan', price: 100, account: 10, // descri1: "ok", // 错误 // stockno: 1000, // 错误 [Symbol('stockno1')]: 1000, 100: 'abc', // true: 1, // 错误 } interface Product3 { name: string, price: number, account: number, [x: symbol]: any } let p3: Product3 = { name: 'zhangsan', price: 100, account: 10, // descri1: "ok", // 错误 // stockno: 1000, // 错误 [Symbol('stockno1')]: 1000, // 100: 'abc', // 错误 // true: 1, // 错误 } interface Product4 { name: string, price: number, account: number, [x: string]: number | string // [x: string]: number // 错误 } let p4: Product4 = { name: 'zhangsan', price: 100, account: 10, // descri1: "ok", // 错误 // stockno: 1000, // 错误 [Symbol('stockno1')]: 1000, // 100: 'abc', // 错误 // true: 1, // 错误 } export { }
索引访问类型,索引访问类型的深入扩展
const symid = Symbol("productno") interface Product { [symid]: number | string, name: string, price: number, account: number, buy(): void } // 重名后合并 interface Product { webchat: string } type A = Product["buy"] type B = Product["price" | "name"] type S = Product[typeof symid] type Pkeys = keyof Product // "name" | "price" | "account" | "buy" | typeof symid let pkeys: Pkeys = "account" // let pkeys2: "name" | "price" | "account" | "buy" | typeof symid = "account"
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现