TypeScript 的核心原则之一是对值所具有的结构进行类型检查。我们使用接口(Interfaces)来定义对象的类型。接口是对象的状态(属性)和行为(方法)的抽象(描述)。
在接口里可以设计只读属性(readonly)和可选属性。
实例:
export {}
//动物接口
interface Animal {
readonly gender: string, //只读属性,一旦赋值后再也不能被改变了。
high: number,
weigh: number,
alias?: string //可选属性
eat(): void //定义方法
}
const a: Animal = {
gender: 'male',
high: 120,
weigh: 60,
eat() {
console.log('eating...');
}
}
console.log(a);
a.eat();
//a.gender = 'female'; //error
readonly vs const 最简单判断该用 readonly 还是 const 的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 const,若做为属性则使用 readonly。
接口继承接口
export {}
//动物接口
interface Animal {
readonly gender: string, //只读属性
high: number,
weigh: number,
alias?: string //可选属性
eat(): void //定义方法
}
const a: Animal = {
gender: 'male',
high: 120,
weigh: 60,
eat() {
console.log('eating...');
}
}
console.log(a);
a.eat();
//a.gender = 'female'; //error
interface Human extends Animal{
name: string,
thinking():void
}
const h : Human ={
gender : 'male',
high: 175,
weigh : 70,
name: 'zhangsan',
eat() {
console.log(this.name+" is eating...");
},
thinking() {
console.log(this.name+" is think...");
}
}
h.eat();
h.thinking();
函数类型
接口能够描述 JavaScript 中对象拥有的各种各样的外形。 除了描述带有属性的普通对象外,接口也可以描述函数类型。例如,定义个编程接口。
//编程接口
interface Programing{
programing(language:string) : void
}
一个类可以实现多个接口
定义一个程序员类,实现Human和Programing接口。
//程序员类
class Programer implements Human, Programing{
readonly gender: string;
high: number;
name: string;
weigh: number;
constructor(gender,high,weight,name) {
this.gender = gender;
this.high = high;
this.weigh = weight;
this.name = name;
}
eat(): void {
console.log(this.name+" is eating...");
}
programing(language: string): void {
console.log(this.name +","+"use "+language+" langauge programing....");
}
thinking(): void {
console.log(this.name+" is thinking...");
}
}
const programer = new Programer('male',180,85,'张三');
programer.programing("Java");