TS Interface-接口 与 函数 鸭子类型


interface不存在于JavaScript 用来做类型的静态检查

// interface Person {
// readonly id: number; // readonly只读属性不允许改变
// name: string;
// age?: number // 加上问号 表示是可选属性
// }

// // let hky: Person = {
// // name: 'hky'
// // }
// // 比接口少一些或者多一些属性是不被允许的
// // Interface.ts:6:5 - error TS2741: Property 'age' is missing in type '{ name: string; }' but required in type 'Person'.

// let hky: Person = {
// id: 123,
// name: 'hky',
// age: 20
// }

// // 报错 只读属性不允许被改变
// hky.id = 123 // => Interface.ts:18:5 - error TS2540: Cannot assign to 'id' because it is a read-only property.

// Function 函数

// 可选参数后不能 添加确定的参数 会使系统类型判断出现混乱

const add = (x: number, y: number, z?: number): number => {  //  箭头不是es6中的箭头函数 而是TS中声明函数类型返回值的方法
  if (typeof z === 'number') {
    return x + y + z
  } else {
    return x + y
  }
}

// 不允许超出 约定参数
// 约定好类型 也不允许改变
// z为可选属性

interface Fun {
  (x: number, y: number, z?: number ): number // interface 声明函数类型
}
// let add2 = (x: number, y: number, z?: number ) => number = add
let add2: Fun = add
//在TS中:后都是声明的类型 与逻辑并没有什么关系

 

// 鸭子类型 (duck typing)  

interface Base {
  id: number
}

interface Advance extends Base {
  name: string
}

const test = (val: Base) => {

}

const a:Advance = { id:1, name: 'jack' }
test({id:12}) // 此时传一个Base定义好的数据肯定是可以的
test(a) // a继承于Base  所以传a 也是没有问题的 类型兼容
// java的类型兼容 与 js的类型兼容是有区别的   鸭子类型 TS 是 面向接口编程而不是面向对象编程
// 此时如果把Advance去掉 就跟  Advance 接口没有任何关系了 但是TS没有报错
const b = { id:1, name: 'jack' }   // 此时接口一样 而 类型不一样  但是成立
test(b)
// 说明函数test 根本不在乎你传入的类型是否是Base 类型  但是只要符合接口的要求 有一个number类型的id  就成立


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM