接口是对行为的抽象,由类来定义对象或函数的类型
初始化 tslint 配置规则
tslint --init
//tslint.json
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {},
"rules": {
"quotemark":[ false],
"semicolon": [false],
"interface-name": [true,"never-prefix"],
"object-literal-sort-keys":[false]
},
"rulesDirectory": []
}
可选属性
interface Vegetable{
color?:string, //可选属性
type:string
}
const getVegetables = ({color,type}:Vegetable)=>{
return `A ${color?(color+''):''} ${type}.`
}
console.log(getVegetables({type:'tomato'}))
A red tomato.
绕过多余参数检查
- as 断言
告诉 TypeScript 传入的类型就是接口类型
interface Vegetable{
color?:string,
type:string
}
const getVegetables = ({color,type}:Vegetable)=>{
return `A ${color?(color+''):''} ${type}.`
}
console.log(getVegetables({type:'tomato',color:'red',size:'24'} as Vegetable))
- 索引签名
interface Vegetable{
color?:string,
type:string,
[prop:string]:any
}
const getVegetables = ({color,type}:Vegetable)=>{
return `A ${color?(color+''):''} ${type}.`
}
console.log(getVegetables({type:'tomato',color:'red',size:'24'}))
- 类型兼容性
interface Vegetable{
color?:string, //可选属性
type:string,
[prop:string]:any
}
const getVegetables = ({color,type}:Vegetable)=>{
return `A ${color?(color+''):''} ${type}.`
}
const vegetableInfo = {type:'tomato',color:'red',size:'24'}
console.log(getVegetables(vegetableInfo))
只读属性
interface ArrInter {
0: string;
readonly 1: number;
}
let arr: ArrInter = ['Hello', 18];
arr1[2] = 19//此处报错
函数类型
interface AddFunc {
(num1: number, num2: number): number
}
/*上下两种写法等价*/
type AddFunc = (num1: number, num2: number) => number
const add: AddFunc = (n1,n2) => n1+n2;
console.log(add(1, 2));
索引类型
interface RoleDic{
[id:string]:string
}
const role1 = {
0:'super_admin' //此处不会报错,会自动把数值转化成字符串
}
接口的继承
interface Vegetable {
color: string
}
interface Tomato extends Vegetable{
radius:string
}
混合类型接口——函数属性
//JS
let countUp = ()=>{
countUp.count++
}
countUp.count=0
countUp()
console.log(countUp.count)
countUp()
console.log(countUp.count)
countUp()
console.log(countUp.count)
1
2
3
//TS
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);
counter()
console.log(counter.count);
counter()
console.log(counter.count);
1
2
3
网友评论