Typescript interface
我来详细展开 接口Interface 的具体用法配合实际例子---1. 基础对象接口// 定义用户接口interface User {id: number;name: string;email: string;}// 使用接口const user: User {id: 1,name: 张三,email: zhangsanexample.com};// ❌ 错误缺少必填字段const badUser: User {id: 1,name: 张三// Error: Property email is missing};---2. 可选属性?interface Product {id: number;name: string;price: number;description?: string; // 可选discount?: number; // 可选}// 可以不带可选字段const phone: Product {id: 101,name: iPhone,price: 6999};// 也可以带上const laptop: Product {id: 102,name: MacBook,price: 12999,description: 轻薄本,discount: 0.9};---3. 只读属性readonlyinterface Point {readonly x: number;readonly y: number;}const p: Point { x: 10, y: 20 };// ❌ 错误无法修改只读属性p.x 100; // Error: Cannot assign to x because it is a read-only property实际场景配置对象interface Config {readonly apiUrl: string;readonly timeout: number;readonly retries: number;}const appConfig: Config {apiUrl: https://api.example.com,timeout: 5000,retries: 3};// 防止运行时意外修改配置// appConfig.apiUrl hack.com; // ❌ 编译错误---4. 函数接口定义函数结构// 定义一个验证函数的接口interface Validator {(value: string): boolean; // 接收string返回boolean}// 实现const isEmail: Validator (value) {return value.includes();};const isPhone: Validator (value) {return /^1[3-9]\d{9}$/.test(value);};// 使用console.log(isEmail(testqq.com)); // trueconsole.log(isPhone(13800138000)); // true带参数的函数接口interface Calculate {(a: number, b: number, operation: add | subtract): number;}const calc: Calculate (a, b, op) {return op add ? a b : a - b;};---5. 索引签名动态属性// 键是字符串值是数字interface ScoreMap {[subject: string]: number;}const scores: ScoreMap {math: 95,english: 88,physics: 92};// 可以动态添加scores.chemistry 90;// ❌ 错误值类型不匹配scores.history A; // Error: Type string is not assignable to type number实际场景缓存/字典interface Cache {[key: string]: any;}const memoryCache: Cache {};memoryCache.user_123 { name: 张三 };memoryCache.order_456 { items: [] };---6. 接口继承extendsinterface Animal {name: string;age: number;}// Dog 继承 Animal并添加自己的属性interface Dog extends Animal {breed: string;bark(): void;}const myDog: Dog {name: 旺财,age: 3,breed: 金毛,bark() {console.log(汪汪);}};多重继承interface Flyable {fly(): void;}interface Swimmable {swim(): void;}// 鸭子会飞也会游泳interface Duck extends Flyable, Swimmable {quack(): void;}const duck: Duck {fly() { console.log(飞); },swim() { console.log(游泳); },quack() { console.log(嘎嘎); }};---7. 接口实现类implementsinterface Database {connect(): void;query(sql: string): any[];close(): void;}// 类必须实现接口的所有成员class MySQLDatabase implements Database {connect() {console.log(连接MySQL);}query(sql: string) {console.log(执行:, sql);return [];}close() {console.log(关闭连接);}}class MongoDatabase implements Database {connect() {console.log(连接MongoDB);}query(sql: string) {// Mongo用不同的语法但接口保持一致return [];}close() {console.log(关闭连接);}}---8. 实际综合案例API 层设计// 请求参数接口interface LoginParams {username: string;password: string;remember?: boolean;}// 响应数据接口interface ApiResponseT {code: number;message: string;data: T;}// 用户信息接口interface UserInfo {id: number;username: string;avatar: string;roles: string[];}// 登录响应类型type LoginResponse ApiResponse{token: string;user: UserInfo;};// 实际使用async function login(params: LoginParams): PromiseLoginResponse {const res await fetch(/api/login, {method: POST,body: JSON.stringify(params)});return res.json();}// 调用login({ username: admin, password: 123456 }).then(res {if (res.code 200) {console.log(登录成功:, res.data.user.username);}});---9. 接口 vs 类型别名快速对比// 接口可以多次声明自动合并interface Window {myApp: any;}interface Window {version: string;}// 最终 Window 有 myApp 和 version 两个属性// 类型别名不能重复声明type Window { myApp: any };// type Window { version: string }; // ❌ 报错// 类型别名适合做复杂类型运算type StringOrNumber string | number;type UserKeys keyof User; // 提取键名---需要我继续展开 泛型 或 类 的具体例子吗
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2495123.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!