携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
大家好,我是吃鱼的老鼠.最近在学习ts,有些心得来分享一下
二.interface (接口)
1. 初识interface
接口的作用就是为类型命名和为代码定义约定,首字母大写
interface Dog {
name: string,
age: number
}
let dog: Dog = {
name: '小西',
age: 2
}
这样写必须name和age都写上,否则会报错
那如果只想写某些参数呢?
2. 可选参数
加个?就可以了
interface Dog {
name?: string,
age?: number
}
let dog: Dog = {
name: '小西',
}
好处:
1. 可以对可能存在的属性进行预定义;
2.可以捕获引用了不存在的属性时的错误; 例如
let dog: Dog = {
color: '斑点', // 引入不存在的属性
}
dog: Dog = {
naem: 'kuku', // 单词拼错了,也会提示
}
3. 只读属性
用 readonly来指定只读属性后就不能修改其值了
interface Cat {
name: string,
readonly isFemale: boolean
}
let cat: Cat = {
name: 'lulu',
isFemale: true
}
cat.isFemale = false //Cannot assign to 'isFemale' because it is a read-only property.
你可以改猫的名字,但不能修改它的性别
4. 使用interface定义函数类型
interface Sum {
(x: number, y: number): boolean
}
const sum: Sum = (x, y) => {
return x > y
}
console.log(sum(12,34)) // false
这个很简单,练习下就理解了
5. 可索引的类型
先看例子
interface StringArray {
[idx: number]: string;
}
let myArr: StringArray;
myArr = ["luck", "cce"];
let myStr: string = myArr[0];
console.log(myStr) // "luck"
当用 number 类型去索引 StringArray时,会得到 string类型的返回值
// 当然也可以用string去索引 string
interface StringStr {
[idx: string]: string;
}
let stringObj: StringStr = {
dog: 'lulu',
cat: 'cimi',
cow: 'nainiu'
}
console.log(stringObj.dog) // "lulu"
当对象上键值对都是string类型时,就可以用interface的索引类型,而不用去一个个的去定义对象上的类型了.
以上就是我对 interface的理解了,欢迎补充.