Typescript 문서 - 03

Typescript 문서 - 03

# Interfaces

타입이나 API등에서 받은 데이터들이 잘못된 경우 종종 에러나 문제가 생길 수 있다. Typescript에서는 interface를 사용하면 데이터 타입 등등 잘 발견하지 못하는 에러들이 발생하지 않도록 방지할 수 있다.

Basic

interface shape {
  color: string;
  width: number;
이런식으로 interface를 작성할 수 있다.

Optional properties

API나 프론트에서 interface에서 선언한 속성 값들이 모두 있지는 않다. 그럴 때에는 아래와 같이 작성해주면 된다.
interface shapes {
  color: string;
  width?: number;
}

function createShape(shape: shapes): {color: string, width?: number} {
  let newShape = {{color: 'yellow'});

  shape.color = newShape.color;
}

let myShape = createShape({color: "black"});
interface를 선언 해놓고, interface 속성 타입과 다른 타입을 넣을 경우 에러가 난다.

Readonly

값을 변경하지 않을 때, 사용한다. 변수 앞에 readonly를 붙여주기만 하면 된다.
interface Point {
  readonly x: number;
  readonly y: number;
}

let p1: Point = {x: 10, y: 20};
p1.x = 5; // Error
맨 처음, 값 할당 이후에는 값을 변경할 수 없다.
배열(Array)도 readonly를 사용할 수 있다. 기본적인 배열 선언은 Array<T>로 선언하지만, readonly는 ReadonlyArray<T>로 선언해준다.
let a: number[] = [1, 2, 3, 4]; 
let ro: ReadonlyArray<number> = a; // this!!!
ro[0] = 12; // Error
ro.push(5); // Error
ro.length = 100; // Error
a = ro; // Error
ReadonlyArray를 일반 Array로 다시 할당하는 것은 좋지 않은 방법이지만, 할 수는 있다.
a = ro as number[];

readonly vs. const

readonlyconst 둘 중 어떤 것을 사용할지 구별하는 방법은 어디에 사용할지를 생각해보는 것이다.
const: 변수(variables)
reaonly: 속성

Using type assertion

let myShape = createShape({ width: 100, opacity: 0.5 } as shapes);
미리 타입을 알 수 있도록 지정해주어 에러를 막는 방법 중 하나다.

Function types

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;
}

Class types

C#이나 Java와 같은 언어로 인터페이스를 사용하는 것이 가장 일반적인 방법
interface ClockInterface {
  currentTime: Date;
}

class Clock implements ClockInterface {
  currentTime: Date = new Date();
  constructor(h: number, m: number) { }
}

Extending Interface

interface Shape {
  color: string;
}

interface Square extends Shape {
  sideLength: number;
}

let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
상속을 받으면 해당 interface에 대한 속성들을 사용할 수 있다. interface는 여러 interface를 확장, 조합하여 사용 가능하다.

Hybrid types

interface Shape {
  (width: number): string;
  line: number;
  reset(): void;
}

function getShape(): Shape {...}

let s = getShape();
s(10); // this
s.reset();
s.line = 5;
s.line = 5처럼 직접 interface 프로퍼티에 값을 대입하지 않아도 s(10)처럼 직접 값을 대입할 수 있다.

댓글

가장 많이 본 글