interface IUser {
name: string
age: number
}
let user: IUser = {name: "张三", age: 22};
console.log(user);
// {name: "张三", age: 22}
? ? ? ? 关键字:extendes
interface IUser {
name: string
age: number
}
let user: IUser = {name: "张三", age: 22};
console.log(user);
// {name: "张三", age: 22}
// 接口可以继承
interface IStudent extends IUser {
}
let student: IStudent = {name: "李四", age: 18};
console.log(student);
// {name: "李四", age: 18}
? ? ? ? 关键字: ?
interface IUser {
name: string
age: number
}
let user: IUser = {name: "张三", age: 22};
console.log(user);
// {name: "张三", age: 22}
// 接口可以继承
// CET6?: 代表CET6是可选参数,可有可无,而CET4参数则必须得有
interface IStudent extends IUser {
CET4: boolean
CET6?: boolean
}
let student1: IStudent = {name: "李四", age: 18, CET4: true};
let student2: IStudent = {name: "李四", age: 18, CET4: true, CET6: false};
console.log(student1);
// {name: "李四", age: 18, CET4: true}
console.log(student2);
// {name: "李四", age: 18, CET4: true, CET6: false}
? ? ? ? 关键字:readonly
interface IUser {
name: string
age: number
}
let user: IUser = {name: "张三", age: 22};
console.log(user);
// {name: "张三", age: 22}
// 接口可以继承
interface IStudent extends IUser {
readonly DNA: string
CET4: boolean
CET6?: boolean
}
let student: IStudent = {name: "李四", age: 18, DNA: "aaaa", CET4: true};
console.log(student);
// {name: "李四", age: 18, CET4: true}
// CET6是可更改的属性
student.CET6 = true;
console.log(student);
// {name: "李四", age: 18, CET4: true, CET6: true}
// 报错 DNA字段是不可修改的,是只读属性
student.DNA = "ddddddd";
// 接口的目的重在约束
interface IFunc {
(name: string): void
}
let f: IFunc = (a: string): void => {
console.log(a);
}
f("aa");
// aa
interface IIndex {
[index: string]: string
}
let index: IIndex = {username: "张三", nickName: "zhangsan"};
console.log(index);
// {username: "张三", nickName: "zhangsan"}
// 接口重在于约束
interface User {
name: string
age: number
sayInfo(): void
}
class Student implements User {
name: string
age: number
sayInfo(): void {
console.log("姓名: " + this.name);
console.log("年龄: " + this.age);
}
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let student: Student = new Student("张三", 18);
student.sayInfo();
// 姓名: 张三
// 年龄: 18