第一中是 readonly 只读取属性不可修改
// 需求:创建人的对象,需要对人的属性进行一定的约束
// id是number类型,必须有,只读的
// name是string类型,必须有
// age是number类型,必须有
// sex是string类型,可以没
接口中对应好每个的个数
? 代表当前属性可有可无
readonly 只允许你读取不可修改
interface iPerson {
readonly id: number,
name: string,
age: number,
sex: string
}
const person: iPerson = {
id: 1,
name: "超人",
age: 35,
sex: '男'
}
person.id = 2;
第二中是 接口定义一个 函数function
// 2、接口定义一个 函数function
interface iSearchFunc {
(source: string, substring: string): boolean
}
// 实现一个在字符串中查找的一个方法,找到就是true 没有就是 flase
const searchString: iSearchFunc = (source: string, substring: string) => {
return source.search(substring) > -1;
}
console.log(searchString('你好啊!李总', '李'));
// 找到就是true 没有就是 flase
return{
searchString
}
第三中 1.接口定义一个 类class
interface iFly {
fly(): string
}
class MyPerson implements iFly { // implements 让当前的类 使用当前的接口
fly(): string {
return '我的高层决定,乘坐煤气罐完成fly的梦想!'
}
}
const person = new MyPerson(); // 实例对象
//console.log(person.fly());
return {
MyPerson
}
2.不建议把属性定义到 interface 上 interface 中定义方法就行
interface iFly {
name: string
fly(): string
}
class MyPerson implements iFly { // implements 让当前的类 使用当前的接口
name: string = 'blue'
fly(): string {
return '我的高层决定,乘坐煤气罐完成fly的梦想!'
}
}
const person = new MyPerson(); // 实例对象
console.log(person.fly());
return {
MyPerson
}
3.多个接口 的使用
interface iFly {
fly(): string
}
interface iSwin {
swin(): string
}
//interface iFly {
// swin(): string
// fly(): string
//}
// 这个方法可以用,但是因为有时候会有多个接口所有,根据实际情况去选择
// implements 让当前的类 使用当前的接口
class MyPerson implements iFly, iSwin {
fly(): string {
return '我是第一个接口'
}
swin(): string {
return '我是多个接口'
}
}
const person = new MyPerson(); // 实例对象
console.log(person.fly());
console.log(person.swin());
return {
MyPerson
}
4.类的继承 和3里的差不多多了一行代码
interface iFly {
fly(): string
}
interface iSwin {
swin(): string
}
// 类的 继承
interface FlyAndSwim extends iFly, iSwin { };
class MyPerson implements FlyAndSwim { // implements 让当前的类 使用当前的接口
fly(): string {
return '我是第一个接口'
}
swin(): string {
return '我是多个接口'
}
}
const person = new MyPerson(); // 实例对象
console.log(person.fly());
console.log(person.swin());
return {
MyPerson
}
数组的类型定义
// var arr: number[] = [12, 34, 45, 56, 78]
// 泛型的写法
var arr1: Array<number> = [12, 34, 35, 56, 67]
var arr2: Array<string> = ['ccc', 'aaa', 'bbb']
var arr3: Array<{ a?: number, b?: number }> = [{ a: 34 }, { b: 43 }]
var arr4: Array<number[]> = [[45, 67], [12, 34]]
var arr5: Array<string | number> = ['ccc', 12, 'ppp']
// 元组
// 所有人的位置和类型一定要对应上
// 个数上也是有所限制的 [string, number, string] = 3个['aa', 12, 'ccc'] 就是3个
const arr6: [string, number, string] = ['aa', 12, 'ccc']
默认的每个都会标注(下标) 而且还是一个递增的关系
// enum Color {
// red,
// green,
// blue
// }
// console.log(Color.red, Color.green, Color.blue);
// return Color
根据下标也可以拿到对应的值
// enum Color {
// red=20,
// green,
// blue
// }
// console.log(Color.red, Color.green, Color.blue);
// return Color
enum Color {
red,
green,
blue = 22
}
console.log(Color.red, Color.green, Color.blue);
console.log(Color[22]);
return Color