区别

类型别名和 接口类似,但最关键的区别还是在于 接口可以通过集成扩展,而别名确定后无法添加新的属性,只能通过并集类型去扩展

接口的定义
  1. //声明类型的两种方式
  2. //通过type定义
  3. // type InfoType = {name:string,age:number}
  4. //通过intetface接口定义 可以定义可读属性 以及可选属性
  5. interface InfoType{
  6. name?:string
  7. readonly age:number
  8. }
  9. const info:InfoType = {
  10. name:'why',
  11. age:18
  12. }
  13. interface LabelValue{
  14. label:string
  15. }
  16. let myObj = { size: 10, label: '123' };
  17. function printLabel(labelObj: LabelValue) {
  18. console.log(labelObj.label);
  19. }
  20. printLabel(myObj);
索引类型和额外属性
  1. //通过interface 定义索引类型
  2. interface IndexLanguage{
  3. [index:number]:string|number
  4. }
  5. const frontLanguage:IndexLanguage = {
  6. 0:"HTML",
  7. 1:"abc" //索引必须number
  8. }
  9. interface ILanguageYear{
  10. [index:string]:number
  11. }
  12. const languageYear:ILanguageYear = {
  13. "C":1972,
  14. "Java":1995,
  15. "Javascript":1996
  16. }
  17. interface SquareConfig {
  18. color?: string;
  19. width?: number;
  20. [propName: string]: any;
  21. }
  22. let newObj: SquareConfig = {
  23. color: "123",
  24. abc: 456,
  25. };
函数类型接口
  1. interface Fc{
  2. (source:string,subString:string):boolean
  3. }
  4. //接口函数相当于是函数的一个签名
  5. //只要参数数量和类型一致,甚至类型都可以不写有类型推导
  6. let mySearch:Fc = function(src:string,sub:string):boolean{
  7. let result = src.search(sub)
  8. return result > -1
  9. }
接口的继承
  1. //接口的继承
  2. interface ISwim{
  3. swimming:()=>void
  4. }
  5. interface IFly{
  6. flying:()=>void
  7. }
  8. //多继承
  9. interface IAction extends ISwim,IFly{
  10. }
  11. const action:IAction = {
  12. swimming(){
  13. },
  14. flying(){
  15. }
  16. }
  17. interface Shape {
  18. color: string;
  19. }
  20. interface PenStroke {
  21. penWidth: number;
  22. }
  23. interface Square extends Shape, PenStroke {
  24. sideLength: number;
  25. }
  26. let squre = {
  27. color: "blue",
  28. sideLength: 10,
  29. penWidth: 5.0,
  30. } as Square;
交叉类型
  1. interface ISwim{
  2. swimming:()=>void
  3. }
  4. interface IFly{
  5. flying:() => void
  6. }
  7. //联合类型 有其中一个就行
  8. type myType1 = ISwim | IFly
  9. //交叉类型 必须都有
  10. type myType2 = ISwim & IFly
  11. const obj1:myType1 = {
  12. flying(){
  13. }
  14. }
  15. const obj2:myType2 = {
  16. flying(){
  17. },
  18. swimming(){
  19. }
  20. }
面向接口实现
  1. interface IEat{
  2. eating:()=>void
  3. }
  4. interface Swim{
  5. Swiming:()=>void
  6. }
  7. //类实现接口
  8. class Animal{
  9. }
  10. //继承只能单继承
  11. //实现接口可以多个
  12. class Fish extends Animal implements IEat,Swim{
  13. eating(){
  14. }
  15. Swiming(){
  16. }
  17. }
  18. class Person extends Animal implements Swim{
  19. Swiming(){
  20. }
  21. }
  22. //实现场景 一些公共的API 面向接口编程
  23. //通过类来实现接口的 方法
  24. function swimAction(swimable:Swim){
  25. swimable.Swiming()
  26. }
  27. //所有实现了Swim接口的类对应的对象 都是可传入的
  28. swimAction(new Fish())
  29. swimAction(new Person())