使用接口几乎可以定义任何结构
基本用法
接口定义几乎任意结构
- 代码
interface Info {
firstName: string;
lastName: string;
}
const getFullName = ({ firstName, lastName }: info) => {
;`${firstName}+${lastName}`
}
这里特别注意的就是 你不要把接口理解为一个在定义一个对象,而是要理解为一个代码块,里面是一条条声明的语句,只不过声明的不是变量的值 而是类型.声明也不用等号赋值,而是用冒号指定类型.每条声明致歉用换行分隔即可,或者也可以使用分号或者都行
可选属性
当我们定义一些结构的时候,一些结构对于某些字段的要求是可选的。有就做处理,没有就忽略.
例如
const getVegetables = ({ color, type }) => {
return `A${color ? color : ''}+${type}`
}
我们可以看到这个函数根据传入对象中的 color 和 type 来进行描述返回一句话,color 是可选的,所以我们应该给 color 设置可选属性,在属性前面加个?即可.
interface Vegetables {
color?: string;
type: string;
}
这里可能 tslint 会报一个警告,说接口应该大写之类的。你可以在 tslint.json 中的 rules 添加”interface-name”: [true, “never-prefix”]来关闭
多于属性检查
- 假如我们多传入了属性,接口上不存在你多余的这个属性。只要接口中没有定义这个属性,就会报错。但是如果你定义了可选 size 属性,上面的例子就不会报错
getVegetables({
type: 'tomota',
size: 'small'
}) //size不在类型Vegetables
绕开多余属性检查
有三种方法
- 第一种使用类型断言
interface Vegetables{
color?:string;
type:string;
}
const getVegetables = ({color,type}:Vegetables)=>{
return `A${color?color+"":""}${type}`
};
getVegetables({
type:"tomato",
size:12,
price:12,
} as Vegetables);
- 第二种添加索引签名
添加字符串索引签名,索引签名后期再说
interface Vegetables {
color: string;
type: string;
[prop: string]: any;
}
const getVegetables = ({ color, type }: Vegetables) => {
return `A${color ? color : ''}${type}`
}
getVegetables({
color: 'red',
type: 'tomato',
size: 12,
price: 12
})
只读属性
- 接口也可以设置为只读性
interface Role{
readonly 0 :string;
readonly 1: string;
}
- 这时候我们试图修改它的值
interface Role{
readonly 0 :string;
readonly 1: string;
}
let role:Role = {
0:"super_role",
1:"admin"
};
role[1] = "super_admin"
//会报错误 Cannot assign to '0' because it is a read-only property
readonly 里面对应属性,const 对应常量。
函数类型
接口也可以描述函数类型
interface AddFunc {
(num1: number, num2: number): number;
}
这里我们定义了一个 AddFunc 结构,这个结构要求实现这个结构的值,必须包含一个和结构里定义的函数一样参数,一样返回值的方法,或者这个值就是符合这个函数要求的函数,我们管花括号里包着的内容为调用签名,它由带有参数类型的参数列表和返回值类型组成。后面学到类型别名的死后还有其他写法
const add: AddFunc = (n1, n2) => n1 + n2
const join: AddFunc = (n1, n2) => `${n1}${n2}`
// 不能将类型string分配给number
add('a', 2)
总结
这讲主要是接口的定义和用法.
接口的只读性