[typeScript语法3]interface

前2篇有错误的原因找到了,本地的ts版本有问题,不是最新版本,是1.8。不改了,就这样写吧,以后注意~~

/**typeScript-3 interface
 * Created by liyanq on 17/6/8.
 */

interface LabelledValue {
    label: string;
}
function PrintLabel(labelledObj: LabelledValue): void {
    console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
PrintLabel(myObj);//Size 10 Object


//--------Optional Properties-----------------//
/*1,createSquare的返回值虽然是{color: string; area: number}类型,但返回多些字段也可以,
 不能少,少了编译器提示错误,可以理解返回值必须是实现了包涵这两个字段的接口的对象~
 2,createSquare的返回值在es5中直接无视~
 3,虽然有可选的字段,但访问接口定义范围外的字段,会有错误提示.~
 */
interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {//注意这里返回值
    let newSquare = {color: "white", area: 100, age: 30};
    if (config.color) {
        // newSquare.color = config.c;// Error: Property 'c' does not exist on type 'SquareConfig'
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({color: "black"});
console.log(mySquare);//{ color: 'black', area: 100 }

//-----------Readonly properties------------//
interface Point {
    readonly y: Number;
    readonly x: Number;
}
let p1: Point = {x: 1, y: 1};
// p1.x = 2;//cannot assign to x because it is a constructor or a read-only property


class Foo {
    b: string;//这里这么就不能设置成readonly???
    constructor(hello: string) {
        this.b = hello;  // 在构造函数中允许赋值
    }
}
let foo = new Foo("Hello");
console.log(foo);//Foo { a: 1, b: 'Hello' }


// let a: Array<number> = [0, 1, 2, 3, 4];
// let b: ReadonlyArray<number> = a;
// b[5] = 5;      // 错误, 元素是只读的
// b.push(5);     // 错误, 没有 push 方法 (因为它会改变数组)
// b.length = 3;  // 错误, length 是只读的
// a = b;         // 错误, 缺少会改变数组值的方法

// const v = { k1: 1, k2: { k21: 2 } };
// const v_ro = v as Readonly<typeof v>;
// 属性: 不可赋值
// v_ro.k1 = 2;
// 属性的属性: 可以赋值
// v_ro.k2.k21 = 3;

//-----------readonly vs const-------//
//Variables use const whereas properties use readonly.

//--------------Excess Property Checks-----------//
interface SquareConfig2 {
    color?: string;
    width?: number;
    [propName: string]: any;
    /*意思是index signatures,中括号里面只能是number或string类型.
     * 自己的理解:一旦接口定义了这个方式,通过索引访问的方法,那么所有的属性都可以通过这个方法访问到,
     * 并且类型能自动的隐式转换,否则接口本身就报错~~!
     * */
}
function createSquare2(config: SquareConfig2): { color: string; area: number } {
    let newSquare = {color: "white", area: 100, age: 30};
    if (config.color) {
        // newSquare.color = config.c;// Error: Property 'c' does not exist on type 'SquareConfig'
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}
let mySquare2 = createSquare2({coulor: "red", width: 100});//这样做,虽然绕开了检查,但也失去了type语言的意义了~~!
// let mySquare2 = createSquare2({coluor: "red", width: 100} as SquareConfig);//这个可以躲过编译器的警告~
console.log(mySquare2);

//------------Function Types------------//
/*
 * 1,在函数类型正确的通过类型检查中,参数的名称不是必须匹配的。*/
interface SearchFunc {
    (source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function (source: string, subString: string): boolean {
    let result = source.search(subString);
    return result > -1;
};
console.log(mySearch("Hello", "H"));

//------------------Indexable Types--------------//
/*错误, 'length'的类型不是索引类型的子类型
 * 索引类型是string,length的类型是number
 * */
interface Dictionary {
    [anyname: string]: string;
    length: string;
}
//-----------------Class Types--------//
/*1,接口定义的方法和字段,在类里面都必须public
 * 2,当用一个类来实现一个接口时,只检查该类的实例部分。由于构造函数位于静态部分,它不包含在该检查中。*/
interface ClockInterface {
    currentTime: Date;
    setTime(d: Date);
}

class Clock implements ClockInterface {
    currentTime: Date;

    public setTime(d: Date) {
        this.currentTime = d;
    }

    constructor(h: number, m: number) {
    }
}

//------------类的静态部分和实例部分的差异-----------------//

interface ClockStatic {
    new (hour: number, minute: number);
}
class Clock2 {
    currentTime: Date;

    constructor(h: number, m: number) {
        this.currentTime = new Date(2017, h, m);
    }
}
var cs: ClockStatic = Clock2;
var newClock = new cs(7, 30);
console.log(newClock);


//----------------接口扩展--------------//
interface Shape {
    color: string;
}
interface PenStroke {
    penWidth: number;
}
interface Square extends Shape, PenStroke {
    sideLength: number;
}
var square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;


//--------------混合类型-----------//
interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}
function counter(): Counter {
    var self = <Counter>function (start: number) {
        self.interval = start;
        console.log("Hello World " + start);
    };
    self.interval = 10;
    self.reset = function () {
        self.interval = 10;
    };
    return self;
}
var c = counter();//c.interval = 10
c(5); //c.interval = 5
c.interval = 15; //c.interval = 15
c.reset(); //c.interval = 10

/*我个人觉得这样写不太好,还是声明成类,然后创建对象的方式比较正规*/
interface Counter_New {
    funStart(start: number): void;
    reset(): void;
    interval: number;
}

class Counter_Class implements Counter_New {
    interval = 10;

    funStart(start: number): void {
        this.interval = start;
        console.log("Hello World " + start);
    }

    reset(): void {
        this.interval = 10;
    };
}

var c2 = new Counter_Class();
c2.funStart(20);
c2.interval = 15;
c2.reset();
//待研究
// interface UIElement {
//     addClickListener(onclick: (this: void, e: Event) => void): void;
// }



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: TypeScript 接口是一种用于描述对象形状的语法结构,它可以定义对象的属性、方法、函数等,以及它们的类型和参数。接口可以用来约束函数的输入和输出,也可以用来定义类的成员。接口可以被继承和实现,从而实现代码的复用和灵活性。在 TypeScript 中,接口是一种非常重要的语言特性,它可以帮助我们更好地组织和管理代码。 ### 回答2: TypeScript中的接口(interface)是用于定义对象的结构和类型的一种语法。接口可以用来描述一个对象应该具有的属性和方法,相当于定义了一个规范。 在TypeScript中,通过interface关键字来声明一个接口。接口可以包含属性、函数、索引器和其他接口等。例如: ```typescript interface Person { name: string; age: number; sayHello(): void; } const person: Person = { name: "Alice", age: 20, sayHello() { console.log("Hello!"); } }; person.sayHello(); // 输出"Hello!" ``` 上述代码中,我们定义了一个名为Person的接口,它包含了name属性(类型为string)、age属性(类型为number)和sayHello方法(没有返回值)。然后,我们创建了一个符合Person接口规范的对象,并调用了sayHello方法。 接口的好处在于它可以提供类型检查,确保我们使用的对象符合接口的定义。如果一个对象不满足接口的要求,TypeScript会在编译时报错。这样可以在开发过程中避免一些常见的错误。 接口还可以用来描述函数类型、类类型等。它可以作为类型注解使用,对函数的输入参数和返回值进行约束,或者用于定义类的实例部分和静态部分的类型。 总而言之,TypeScript的接口是一种强大的工具,它可以帮助我们在开发过程中更好地定义和约束对象的结构和类型,提高了代码的可读性和可维护性。 ### 回答3: TypeScript中的接口(interface)是用来定义对象的结构和类型的。接口可以定义对象的属性、方法和可选属性等。 通过接口的方式可以明确定义一个对象应该具有的属性和方法,以及它们的类型。一旦定义了接口,就可以使用它来强制对象符合这个接口定义的结构。 接口的定义与类的定义有些类似,但是接口是一种抽象的概念,不能直接被实例化。它可以被类、对象、函数等来实现或者继承。当一个类实现了一个接口时,它必须实现接口中定义的所有属性和方法。 使用接口可以有效地帮助我们进行代码的重用和维护。当一个对象需要满足多个接口时,可以使用逗号将多个接口名进行分隔,在该对象中实现这些接口定义的属性和方法。 同时,接口还可以用来定义函数的参数类型和返回值类型。通过指定函数参数和返回值的接口定义,可以限制函数的使用范围,并提供更明确的类型检查。 总结起来,TypeScript中的接口是用来定义对象结构和类型的一种机制。它可以帮助我们明确对象的属性和方法,并提供类型检查。使用接口可以增加代码的可读性、可维护性,并提高代码的重用性和健壮性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值