ts-接口

interface SquareConfig {
  color?: string;
  width?: number;
}

interface Point {
    readonly x: number;
    readonly y: number;
}



let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
// ro[0] = 12; // error!
// ro.push(5); // error!
// ro.length = 100; // error!
// a = ro; // error!
a = ro as number[];//重写

 // 做为变量使用的话用const,若做为属性则使用readonly。


//======================================

// 函数名(): 返回数据类型
function createSquare(config: SquareConfig):{
     color: string;
      area: number;
}{
    let newSquare{
        color: '#fff';
          area: 100;
    };
    if (config.color) {newSquare.color =config.color}

    // Math.pow(4,3); 
    if (config.width) {newSquare.area =Math.pow(config.width,2);}

     return newSquare;
}
let mySquare = createSquare({color: "black"});

console.log(mySquare);

// 带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?符号。
// 可选属性的好处之一是可以对可能存在的属性进行预定义


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 });
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

interface SquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any;
}


function createSquare(config: SquareConfig): { color: string; area: number } {
    // ...
}
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);

 

posted @ 2017-08-31 11:37  alan-alan  阅读(163)  评论(0编辑  收藏  举报