You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
interfaceArrayInterface{[index:number]:string}letarr:ArrayInterface=[1,'2']// he expected type comes from this index signatureletarr:ArrayInterface=['1','2']
typescript(四) - 接口
接口
接口一方面可以在面向对象编程中表示为行为的抽象,另外可以用来描述对象的形状
约束对象
我们来看下如何使用接口来约束对象
我们发现通过接口
SpeakInterface
约束的对象必须有speck
方法和name
属性但是如果我们的对象有很多未知的属性的时候, 我们可以这样做
通过
[propName: string]: any
来表示对象的其他属性的值是any
如果我们需要定义对象的某一个属性的值的类型的时候我们可以这样做
我们通过接口约束对象属性的值只能是
string
约束类
接口不仅可以约束对象, 在开发中我们经常用来约束类
同样的, 被约束的类必须要有接口约束的属性。而且一个类可以受多个接口的约束。
约束函数
我们可以通过接口约束函数的参数类型和返回值类型
约束数组
我们可以通过以下巧妙的方法约束数组
我们可以理解为, 数组其实也是一个对象, 不过对象中的键是索引0~N , 所以我们可以通过
[index:number]:string
来约束数组每一项的类型接口可以继承接口
看完了日常开发中接口的用法,我们来看下接口的一些特殊用法
代码中接口
EatInterface
继承了接口SpeakiInterface
, 所以等同于类Person
受两个接口约束接口中使用readonly
被接口约束的
readonly
属性是只读的The text was updated successfully, but these errors were encountered: