[typescript] Interface

Suyeon·2020년 11월 10일
0

Typescript

목록 보기
2/12

Object의 구조를 정의하는 새로운 타입을 만듭니다.

  • 순서 상관 없음

Example

interface LabeledValue {
  label: string;
}

function printLabel(labeledObj: LabeledValue) {
  console.log(labeledObj.label);
}

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

Optional Property

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

function createSquare(config: SquareConfig): { color: string; area: number } {
  let newSquare = { color: "white", area: 100 };
  if (config.color) {
    newSquare.color = config.color;
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

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

Readonly properties ("?")

// (1) object
interface Point {
  readonly x: number;
  readonly y: number;
}

let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!

// (2) array
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;

ro[0] = 12; // error!
ro.push(5); // error!

a = ro as number[]; // override it with a type assertion.
ro[0] = 12; // OK

Extra properties

  • It only works if the variable has any common object property.
interface SquareConfig {
  color?: string;
  width?: number;
  [propName: string]: any; // (*)
}

let squareOptions = { colour: "red", width: 100 }; // (**) colour
let mySquare = createSquare(squareOptions);

Extending Interfaces

interface Shape { // (*)
  color: string;
}

interface Square extends Shape { // (**)
  sideLength: number;
}

let square = {} as Square;
square.color = "blue";
square.sideLength = 10;

Multiple Interfaces

interface Shape {
  color: string;
}

interface PenStroke {
  penWidth: number;
}

interface Square extends Shape, PenStroke { //(*)
  sideLength: number;
}

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

Function Type

  • For function types to correctly type check, the names of the parameters do not need to match.
interface SearchFunc {
  (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;

mySearch = function (src: string, sub: string): boolean {
  let result = src.search(sub);
  return result > -1; // return boolean
};

Class Type

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

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

0개의 댓글