typescript-接口

typescript核心的原则就是对值所具有的结构进行类型检查

1) 错误处理error: 'colour' not expected in type 'SquareConfig'
对象字面量被定义一个interface,当作为参数传递或者赋值的时候,如果一个子项字面量存在一个没有被interface定的属性的时候,你会得到一个错误。

interface SquareConfig {
    color?: string;
    width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
    // ...
}
// error: 'colour' not expected in type 'SquareConfig'
let mySquare = createSquare({ colour: "red", width: 100 });

解决办法:
1)使用类型断言跳过检查

let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

2)添加一个字符串索引签名

// SquareConfig可以有任意数量的属性,并且只要它们不是color和width,那么就无所谓它们的类型是什么
interface SquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any;
}

疑问

interface SquareConfig {
    color?: string;
    width?: number;
}
    
function createSquare(config: SquareConfig){
   console.log('config',config)
 }
    // 为什么这段检查不会报错  ?? 
    // 跳过这些检查的方式,这可能会让你感到惊讶,它就是将这个对象赋值给一个另一个变量: 因为 squareOptions不会经过额外属性检查,所以编译器不会报错。
    // const squareOptions = { colour: "red", width: 100 };
    // const mySquare = createSquare(squareOptions);
    
    const mySquare = createSquare({ colour: "red", width: 100 });

2)实现接口

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date);
}

class Clock implements ClockInterface {
    currentTime: Date;
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}

3)继承接口
一个接口可以继承多个接口,创建出多个接口的合成接口。

interface Shape {
    color: string;
}
interface PenStroke {
    penWidth: number;
}
interface Square extends Shape, PenStroke {
    sideLength: number;
}

let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;

4)混合类型
有时你会希望你的对象能同时拥有多种类型
一个例子,一个对象同时希望作为函数和对象使用并且有额外的属性

**5)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 众所周知,在传统的JavaScript中是没有接口的概念的,所谓的接口,其实就是描述集合属性的类型的一个特殊...
    两行代码三个Bug阅读 1,235评论 0 0
  • TypeScript的核心原则之一是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”...
    2o壹9阅读 3,788评论 0 48
  • 介绍 TypeScript的核心原则之一是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类...
    凌统丶阅读 3,328评论 0 1
  • 接口 TypeScript 的核心原则之一是对值所具有的结构进行类型检查。它有时被称做“鸭式辨型法”或“结构性子类...
    罗彬727阅读 1,898评论 0 0
  • 介绍 TypeScript 的核心原则之一是对值所具有的结构进行类型检查。它有时被称做 鸭式辨型法 或 结构性子类...
    24KBING阅读 1,540评论 0 0