typescript中的接口
TypeScript的核心原则之一是对值所具有的结构进行类型检查。
视频教程地址
接口采用 interface
作为关键词
接口的成员属性类型可以是
- number
- string
- Boolean
- any
- enum
- tuple
等ts的基本数据类型,如下代码为ts的一个接口
interface lee {
name: string
age?: number
readonly description: string,
sayHello: () => void,
languages: string[],
}
接口说明
-
age?: number
属性成员后面加个?表示该属性是可选的 -
readonly description
属性成员前面加上readonly,说明是只读的,不可以二次赋值 -
languages: string[]
属性成员的返回值是字符串数组
实现接口
const arg: lee = {
name: '乐编码',
description: "快乐编码,快乐生活!",
sayHello: () => {
console.log("你好!")
},
languages: ["js", 'ts', 'go', 'php']
}
测试一下
const f = (a: lee) => {
a.sayHello()
console.log(a.languages)
}
f(arg)
运行结果
你好!
[ 'js', 'ts', 'go', 'php' ]
接口的继承
interface lee2 extends lee {
height: number
}
采用类实现接口
class hanyun implements lee2 {
name = '乐编码'
description = "快乐编码,快乐生活!"
languages = ["js", 'ts', 'go', 'php']
height = 100
sayHello() {
console.log('hello,我会这么多语言')
console.log(this.languages)
}
}
let func=new hanyun()
func.sayHello()
运行结果
hello,我会这么多语言
[ 'js', 'ts', 'go', 'php' ]
ps 接口的目的是给给我们添加约束,是一种契约精神的体现。定义了就要遵守实现!