笔记。
// 一、接口定义对象
interface NameInfo {
firstName: string
lastName: string
}
const getFullName = ({ firstName, lastName }: NameInfo) => {
return `${firstName} ${lastName}`
}
getFullName({
firstName: 'aahah',
lastName: 'heihei'
})
interface VegetableInfo {
color?: string
readonly type: string // 只读属性
[prop: string]: any // 2.索引签名
}
const getVegetables = ({ color, type }: VegetableInfo) => {
return `A ${color ? color : 'black'} ${type}`
}
getVegetables({ color: 'green', type: 'broccoli'})
getVegetables({ type: 'tomato'})
// *******多给参数会报错 解决方法3种********
getVegetables({ type: 'potato', size: 20 } as VegetableInfo) // 1.类型断言
// 3. 类型兼容性
const vagetable = {
type: 'spinage',
color: 'green',
size: 33
}
getVegetables(vagetable) // 包含VegetableInfo所有属性 多了无所谓
let vagetableObj: VegetableInfo = {
type: 'carrot'
}
// vagetableObj.type = 'radish' 测试readlony属性
// 二、接口定义数组
interface ArrInter {
0: number
readonly 1: string
}
let arr9: ArrInter = [1, 'll']
arr9[0] = 66
// arr9[1] = 'heiheihei' 测试readlony属性
// 三、接口定义函数
// interface AddFunc {
// (num1: number, num2: number): number
// }
// 上述会报warning tslint建议这样写
type AddFunc = (num1: number, num2: number) => number
const add: AddFunc = (n1, n2) => n1 + n2
// 四、接口定义索引类型
interface RoleDic {
[id: number]: string
}
const role: RoleDic = {
1: 'super_admin'
}
// 接口的继承
interface Vegetables {
color: string
}
interface Tomatos extends Vegetables {
radius: number
}
interface Carrot extends Vegetables {
length: number
}
const tomato1: Tomatos = {
radius: 1,
color: 'red'
}
const carrot1: Carrot = {
length: 10,
color: 'orange'
}
// 五、混合类型接口
interface Counter {
(): void,
count: number
}
const getCounter = (): Counter => {
const c = () => {
c.count++
}
c.count = 0
return c
}
const counter: Counter = getCounter()
counter()
console.log(counter.count) // 如果console.log报警告
counter()
console.log(counter.count) // 在tslint.json里面的rules里面加上 "no-console": false
counter()
console.log(counter.count)
counter()
console.log(counter.count)
题外话:这三天睡眠很糟糕,昨天两点多还很清醒,起来把酸奶过滤了一下,站在客厅发呆喝椰子水,躺着闭上眼睛正念练习三十分钟居然完整的做完了,看着天从橘黄色变成黑色再变成深蓝浅蓝灰白。头疼炸裂。