zoukankan      html  css  js  c++  java
  • TS学习之接口

    TypeScript的核心原则之一是对值所具有的结构进行类型检查。接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

    interface testType {
        name: string;
        age: number;
    }  
    function test(obj: testType): void {
        console.log(obj.name);
        console.log(obj.age);
    }
    test({name:"fred",age:20,height:180})
    //fred  20

    interface:接口关键字,只要传入的对象满足接口的必要条件,那么它就是被允许的。

    可选属性(接口定义中加“?”)

    interface testType {
        name: string;
        age?: number;
    }

    只读属性(readonly)

    interface testType {
        readonly name: string;
        readonly age: number;
    }
    
    let test1:testType = {name:"fred",age:20}
    test1.name = "Bob"; //error

    额外的属性检查

    interface testType {
        name?: string;
        age?: number;
    }
    
    function test(conf: testType): void {
    
    }
    
    test({ nama: "fred", age: 20 }) //error:'nama' dose not exist in type 'testType'

    解决方法:a) 断言

    test({ nama: "fred", age: 20 } as testType) //断言

        b)字符串索引签名

    interface testType {
        name?: string;
        age?: number;
        [propName:string]:any;  //字符串索引签名
    }

        c)中间变量绕过类型检测

    let test2 = { nama: "fred", age: 20 }; //中间变量绕过类型检测
    test(test2)

    接口继承(extends)

    interface nameFace {
        name: string;
    }
    interface ageFace {
        age: number;
    }
    interface heightFace extends nameFace, ageFace {
        height: number;
    }
    
    let person = <heightFace>{};
    person.name = "fred";
    person.age = 20;
    person.height = 180;

     接口继承类

    class Point {
        x: number;
        y: number;
    }
    
    interface Point3d extends Point {
        z: number;
    }
    
    let point3d: Point3d = {x: 1, y: 2, z: 3};
  • 相关阅读:
    使用supervisor做进程控制
    HDU 4272 LianLianKan [状态压缩DP]
    UVALive 4297 First Knight [期望+高斯消元(优化)]
    HDU 4269 Defend Jian Ge [模拟]
    POJ 2497 Widget Factory [高斯消元解同余方程组]
    HDU 2996 In case of failure [KD树]
    HDU 4268 Alice and Bob [贪心]
    HDU 4273 Rescue [三维几何]
    HDU 4267 A Simple Problem with Integers [树状数组]
    HDU 4271 Find Black Hand [最短编辑距离DP]
  • 原文地址:https://www.cnblogs.com/sghy/p/7729066.html
Copyright © 2011-2022 走看看