对象类型
let preson: {
name: string;
age: number;
// sayHi(): void;
//也可以使用箭头函数
sayHi: () => void;
} = {
name: '张三',
age: 18,
sayHi() {
console.log('hi');
},
};
可选参数 (属性名后加?)
比如我们在发送axiosget请求时,可以忽略method
function myAxios(config: { url: string; method?: string }) {
console.log(config);
}
myAxios({
url:'xxxx/xxxx/xxx'
})
接口描述对象的类型(interface)
当一个对象类型被多次使用时,一般会使用接口来描述对象的类型,达到复用的目的
interface IPerson {
name: string;
age: number;
sayHi: () => void;
}
let person1: IPerson = {
name: '张三',
age: 18,
sayHi() {
console.log('hi');
},
};
let person2: IPerson = {
name: '李四',
age: 20,
sayHi() {
console.log('hi');
},
};
扩展:interface和type(类型别名)的对比
interface IPerson {
name: string;
age: number;
sayHi: () => void;
}
type IPerson = {
name: string;
age: number;
sayHi: () => void;
}
/*
相同点:都可以为对象指定类型
不同点:1.接口,只能为对象指定类型
2.类型别名,不仅可以为对象指定别名,实际上可以为任意类型指定别名
*/